#!/usr/local/bin/perl5 
#
# insert-move: Given a move filename, we're going to insert an
# HTML link to it in the master.html file at the point marked by
# <!-- INSERT HERE -->
#
# Usage: insert-move master.html
# Input is on stdin, in this format:
# 	filename (format is: Player[ext]-DD-MM-YY.html)
#	move #
# Anchors should be:
# <li><a href="moves/<move#>/<filename>">
# <filename> (Reparsed to look nicer)
# </a>

die if eof(STDIN);
$file = $ARGV[0];
chop($fname = <STDIN>);
chop($moveno = <STDIN>);
$tmp = "/tmp/insert-move.$$";
$marker = "\<!-- INSERT HERE --\>";
$anchor = $fname;
$anchor =~ s/\.html//;
if ($anchor =~ s/^([A-Za-z]+)(\d+)/$1/) {
  $addendum = $2;
}
$anchor =~ s/-9(\d)$/-199$1/;
$anchor .= ")";
$anchor .= " Addendum $addendum" if $addendum;
$anchor =~ s/([a-z])-/$1 (/;

system '/bin/cp', $file, "$file~";

die unless open(IN,$file);
die unless open(OUT,">$tmp");

while (<IN>) {
  if (/$marker/) {
    print OUT "  <li><a href=\"moves/$moveno/$fname\">$anchor</a>\n";
  }
  print OUT;
}
close(OUT);
close(IN);

system '/bin/mv', $tmp, $file;
chmod(0644,$file);

exit 0;
