#!/usr/bin/env ruby
# Tiny eRuby --- ERB2 + CGI
# 	Copyright (c) 2000,2002 Masatoshi SEKI 
#       You can redistribute it and/or modify it under the same terms as Ruby.

require 'erb'

class ERBCGI
  include ERB::Util

  def initialize(f=$<)
    @body = ''
    @head = {}
    @src = read_script(f)
  end
  attr_accessor(:body)
  attr_accessor(:head)
  attr_reader(:src)

  def put
    put_head
    put_body
  end

  private
  def read_script(f)
    cmd = f.gets		# #!/usr/local/bin/ruby ...
    src = f.read
    src = cmd + src unless cmd =~ /^#/
    raise 'source: not found' unless src
    src
  end

  def put_head
    @head['Content-Type'] = "text/html" if @head['Content-Type'].nil?
    @head.each do |k, v|
      puts "#{k}: #{v}\r\n"
    end
    puts "\r\n"
  end

  def put_body
    print @body
  end
end

if __FILE__ == $0
  f = $<
  if ENV['PATH_TRANSLATED']
    f = open( ENV['PATH_TRANSLATED'] )
    $:.unshift(File.dirname(ENV['PATH_TRANSLATED']))
  elsif ENV['SCRIPT_FILENAME']
    $:.unshift(File.dirname(ENV['SCRIPT_FILENAME']))
  end
  _erb = ERBCGI.new( f )
  erb = ERB.new(_erb.src, nil, false, '_erb.body')
  str = erb.result
  _erb.put
end

