#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'cgi'
require 'kconv'
require 'sqlite3'

c = CGI.new(:accept_charset => "UTF-8")
print("Content-type: text/html; charset=UTF-8\n\n")

def cat(file)
  open(file){|f| print f.read}
end
def content(file)
  open(file){|f| f.read.toutf8}
end

fromcgi	= c["fc"]
fields	= ["sid", "namae", "course"]
value	= Hash.new

field_cls = Hash.new("")
for f in fields
  value[f] = c[f]
  field_cls[f] = ""
end
invalid_cls=' class="e"'

cat("header.html")

# puts("<pre>")
# print ENV.collect{|k,v| sprintf("%s=%s\n", k, v)}.join
# puts("</pre>")
if %r,https://tmp.gentei.org/, =~ ENV["HTTP_REFERER"] then
  #
elsif %r,https://www.yatex.org/gitbucket/, !~ ENV["HTTP_REFERER"] then
  puts("<p>ガイダンスWebからのみ利用できます。</p>")
  exit 0
end

sid_invalid = (/^c11.....?$/i !~ value["sid"])

if value.values_at(*fields).index("") || sid_invalid then
  if fromcgi == "yes" then
    if value.values_at(*fields).index("") then
      puts("<p><em>全ての項目を埋めてください</em></p>")
      for f in fields
        c[f] == "" and field_cls[f] = invalid_cls
      end
    end
    if sid_invalid then
      puts("<p><em>正しい学籍番号を入れてください</em></p>")
      sid=""; sid_cls = invalid_cls
    end
  end
  form = content("form.html")
  for f in fields
    form.sub!("__"+f.upcase+"__", value[f])
    form.sub!("__"+f.upcase+"IV__", field_cls[f])
  end
  print form
else
  # if all values filled
  sid = value["sid"][0..6].downcase
  namae = value["namae"]
  course = value["course"]
  mbody = "ITパスポート勉強会2019春の参加を希望します。\n" +
    sprintf("学籍番号:\t%s\n氏名:\t\t%s\nコース:  \t%s\n",
            sid, value["namae"], value["course"])
  open("| sendmail -f 'www@gentei.org' yuuji@gentei.org", "w") do |m|
    m.print(<<-EOF)
To: yuuji@gentei.org
Subject: Ipass application
Mime-Version: 1.0
Content-type: text/plain; charset=iso-2022-jp

	EOF
    m.write(mbody.tojis)
  end
  printf("<p>以下の内容で送信しました。</p>\n<pre>%s</pre>\n", mbody)
  # Finally put record into db
  db = SQLite3::Database.new("db/ipass.sq3")
  db.execute(<<-EOF)
	CREATE TABLE IF NOT EXISTS ipass(
		sid PRIMARY KEY NOT NULL, uname, course);
	EOF
  db.execute("REPLACE INTO ipass VALUES(?, ?, ?)", sid, namae, course)
end
