#!/usr/local/bin/perl5
#
#
# rwhtml - take a riverworld player move email and reformat it
# for html. Automatically creates an html file from stdin.
#
# Output filename and move# on stdout
#
#

while (<STDIN>) {
  last if /^$/;
  chop;
  if (/(\w+): (.*)/) {
	$hdr{$1} = $2;
  }
}

$sub = $hdr{"Subject"};
$sub =~ /\[(.*)\]/;
$sub = $1;
@date = split(" ",$hdr{"Date"});
$date = join("-",@date[1..3]);
#$hdr{"From"} =~ s/\</&lt;/g;
#$hdr{"From"} =~ s/\>/&gt;/g;

# Figure out the directory by figuring out which turn is yet to play
opendir(DIR,'/home/alansz/rw/turns');
@files = readdir(DIR);
closedir(DIR);
@files = reverse sort byturn grep(s/turn(\d+)/$1/,@files);
$nextturn = $files[0] + 1;
$dir = "/home/alansz/www/rw-pbem/moves/$nextturn";

$ext = "";
$file = $sub . $ext ."-".$date.".html";
while (-r "$dir/$file") {
  $ext++;
  $file = $sub.$ext."-".$date.".html";
}

die unless open(OUT,">$dir/$file");

print OUT "<html><head><title>\n";
print OUT $hdr{"Subject"}," ($date)\n";
print OUT "</title></head><body><pre>\n";
#print OUT "From: ",$hdr{"From"},"\n";
print OUT "Date: ",$hdr{"Date"},"\n";
print OUT "Subj: ",$hdr{"Subject"},"\n\n";

while (<STDIN>) {
  s#\&#&amp;#g;
  s#\<#&lt;#g;
  s#\>#&gt;#g;
  s#\{\s*#<i>Plan:\n#g;
  s#\s*\}#</i>#g;
  s#\[\s*#<i>To GM:\n#g;
  s#\s*\]#</i>#g;
  s#^#<hr>#g;
  print OUT;
}

print OUT "\n</pre></body></html>\n";
close(OUT);

print $file,"\n";
print $nextturn,"\n";
chmod(0644,"$dir/$file");

exit 0;

# Sort words of the form turn# by the #.
sub byturn {
  local($c,$d) = ($a,$b);
  $c =~ s/turn//;
  $d =~ s/turn//;
  return $c <=> $d;
}
