#!/usr/bin/ruby

# compresseur de rapport de combat Moutyhall
# Licence GPL - 2007 - par tyrollus 72681 (Yoann Guillot)

require 'mh_resumemsg'

def parsehttp(s, sep='&')
	s.to_s.split(sep).inject({}) { |h, a|
		k, v = a.split('=', 2).map { |s| s.gsub('+', ' ').gsub(/%(..)/) { $1.hex.chr } }
		h.update k => v
	}
end

postdata = parsehttp $stdin.read
cookie   = parsehttp ENV['HTTP_COOKIE'], /\s*;\s*/

sender = postdata['sender'] || cookie['mhpogo_sender']
mm     = postdata['mm']     || cookie['mhpogo_mm']

sendcookie = {}
sendcookie['mhpogo_sender'] = sender if sender
sendcookie['mhpogo_mm']     = mm     if mm

puts "content-type: text/html\r\n"
sendcookie.each { |k, v|
	puts "set-cookie: #{k}=#{v.gsub(/(\W)/) { "%%%02x" % $1[0] } }; expires=#{(Time.now + 30*24*3600).strftime('%a, %d-%b-%Y 00:00:00 GMT')}; domain=guillot.iiens.net; path=/cgi-bin/\r\n"
}
puts "\r\n"

def htmlesc(s)
	s.gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;')
end
	
def unhandled(l)
	puts "<!-- unhandled #{htmlesc l.chomp} -->"
end

puts <<EOH
<html>
 <head>
  <title>The Official Pogo Kompressor</title>
  <style>
#kompress {
	background-color: #CCF;
	margin: 20px;
	padding: 10px;
}
form {
	background-color: #DDD;
	margin: 20px;
	padding: 20px;
}
body {
	width: 800px;
	margin: auto;
}
textarea {
	width: 100%;
	margin-bottom: 20px;
}
  </style>
 </head>
 <body>
EOH

if postdata['q']
puts <<EOH
  <div id="kompress">
   <center>#{htmlesc(resume(sender, postdata['q'], (mm.to_i if mm.to_i != 0)))}</center>
  </div>
EOH
end

puts <<EOH
  <form method="post">
   Nom du troll impliqué: <input type="text" name="sender" value="#{htmlesc(sender || 'Votre troll')}" /> 
   Maitrise magique: <input type="text" name="mm" value="#{htmlesc(mm || '0')}" /><br />
   Rapport du combat:<br/>
   <textarea name="q" rows=30></textarea><br />
   <input type="submit" value="Kompresser !" style="width: 100%"/>
  </form>
 </body>
</html>
EOH