#!/usr/local/bin/ruby
# Tiny Tiny eRuby --- ERbLight + CGI
# 	Copyright (c) 2000 Masatoshi SEKI 
#       You can redistribute it and/or modify it under the same term as Ruby.
# 	$OrigId: erbcgi.rb,v 1.3 2000/04/23 15:09:10 mas Exp $
#	$Id: erbcgi.rb,v 1.5 2002/02/15 15:48:59 seki Exp $
# 	$Author: seki $

require 'erb/erbl.rb'

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

  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

  private
  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

  private
  def put_body
    print @body
  end

  public
  def put
    put_head
    put_body
  end

  public
  def escape_html(s)
    s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
  end
  alias h escape_html
  
  public
  def escape_url(s)
    s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
  end
  alias u escape_url

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 = ERbLight.new(_erb.src, nil, false, '_erb.body')
  str = erb.result
  _erb.put
end

