#!/usr/bin/ruby

class HTTP404 < Exception
end

class App

  DATADIR="/var/db/wxod"
  LIBDIR="/var/lib/wxod"

  def initialize
    @odata = []
    @otype = "text/plain; charset=utf8"
    @path = ENV['PATH_INFO']
    @fmt = case @path
      when /\.csv$/ then :csv
      when /\.html$/ then :html
      else nil
      end
  end 

  attr_reader :path, :fmt

  def puts str
    str = str.sub(/$/, "\r\n") unless /\r\n$/ === str
    @odata.push str
  end

  def list ary, cfg = {}
    case @fmt
    when :csv
      for row in ary
        puts row.to_a.map{|word|
	  (/,/ === word) ? ('"' + word.gsub(/"/, '""') + '"') : word
	}.join(',')
      end
    else
      puts "<html><head><title>#{@path}</title></head><body>"
      puts "<h1>#{@path}</h1>"
      puts "<p id='versions'>Versions: "
      puts "<a href='index.csv'>CSV</a> "
      puts "<a href='index.html'>HTML</a>"
      puts "</p><hr>"
      puts "<ul id='main'>"
      puts "<li><a href=\"any/\">any</a></li>" if cfg[:show_any]
      sub = '/' + (cfg[:linkto] || '') 
      for row in ary
        word = row.to_a.first
        ins = ([''] + row.to_a[1..-1]).join(' ')
        puts "<li><a href=\"#{word}#{sub}\">#{word}</a>#{ins}</li>"
      end
      puts "</ul>"
      puts "<hr>"
      puts "</body>"
      @otype = "text/html; charset=utf8"
    end
  end

  def table ary, cfg = {}
    case @fmt
    when :csv
      for row in ary
        puts row.to_a.map{|word|
	  (/,/ === word) ? ('"' + word.gsub(/"/, '""') + '"') : word
	}.join(',')
      end
    else
      puts "<html><head><title>#{@path}</title></head><body>"
      puts "<h1>#{@path}</h1>"
      puts "<p id='versions'>Versions: "
      puts "<a href='data.csv'>CSV</a> "
      puts "<a href='data.html'>HTML</a>"
      puts "</p><hr>"
      puts "<table id='main' border='1'><thead></thead><tbody>"
      #puts "<li><a href=\"any\">any</a></li>" if cfg[:show_any]
      for row in ary
        puts "<tr>" + row.to_a.flatten.map{|s| "<td>#{s}</td>" }.join + "</tr>"
      end
      puts "</tbody></table>"
      puts "<hr>"
      puts "</body>"
      @otype = "text/html; charset=utf8"
    end
  end

  def main
    case @path
    when %r{^/*(?:index(?:\.\w+)?)?$}
      list ['amd']
    when %r{^/amd(/.*)$}
      rel = $1
      load File.join(LIBDIR, 'wxod-amd.rb')
      Amd.new(self, rel).run
    else
      raise HTTP404
    end
  end

  def run
    main
    print "Date: #{Time.now.utc}\r\n"
    print "Content-Type: #{@otype}\r\n\r\n"
    for line in @odata
      print line
    end
  rescue HTTP404 => e
    print "Status: 404 Not Found\r\n"
    print "Content-Type: text/plain\r\n\r\n"
    print "PATH_INFO=#{@path.inspect}\r\n"
    print e.message + "\r\n at " + e.backtrace.join("\r\n\t")
  rescue Exception => e
    print "Status: 500 Internal Server Error\r\n"
    print "Content-Type: text/plain\r\n\r\n"
    print e.message + "\r\n#{e.class} at " + e.backtrace.join("\r\n\t")
  end

end

App.new.run
