#!/usr/bin/perl
# insert-date.pl
# update the weeklist.sel file, which is included in the web pages using SSI
# so they have the current list of reports
# don't keep more than $MAXWEEKS dates in the file

$MAXWEEKS=104;			# keep this many weeks in the form

if ($#ARGV != 1) {
  print "usage: insert-date.pl weekfile homepage

e.g.:  insert-date.pl thisweek index.html\n";
  exit;
};

$weekfile = $ARGV[0];
$infile   = $ARGV[1];
$outfile = "$infile.~tmp~";

if (!open(DATEFILE, "<$weekfile")) {die "can't open $weekfile: $!"}
chop($thiswk=<DATEFILE>);	# report date in the form "Aug 16, 1997"
chop($thisrep=<DATEFILE>);	# report date in the form 19970816
close(DATEFILE);

if (!open(INFILE,  "<$infile"))  {die "can't open $infile: $!"}
if (!open(OUTFILE, ">$outfile")) {die "can't create $outfile: $!"}
$nweeks=0;
while (<INFILE>) {
    if (/<select name=repdate/) {
	print OUTFILE $_;
	$_ = <INFILE>;
	die "insert-date has already run today [$thisrep]\n"
				if /$thisrep/;
	print OUTFILE "<option value=$thisrep selected>$thiswk\n";
	s/ selected//;
	print OUTFILE $_;	# previous week
	$nweeks=2;
	last;
    } else {
	print OUTFILE $_;
    }
}
die "<select name=repdate> not found in $infile\n" if $nweeks == 0;

while (<INFILE>) {
    if (m|</select>|) {		# found </select>
	print OUTFILE $_;	# we are done
	last;
    } elsif ($nweeks < $MAXWEEKS) { # keep this many, at most
	print OUTFILE $_;
	$nweeks++;
    }
}

print OUTFILE <INFILE>;		# copy the rest of the file

close(INFILE);
close(OUTFILE);
rename($outfile, $infile);	# out with the old, in with the new
print "web usage reports select list in $infile
   contains $nweeks weeks of reports, ending with $thiswk\n";
