#!/usr/bin/perl

($#ARGV == 1) || (die "usage: $0 <slokafile> <numberfile>");

$slokafile = $ARGV[0];
$numfile = $ARGV[1];
$sarga = $1 if ($slokafile =~ /up(.*?).txt/);

# get the number of the Sloka to post, from the number file.
open(NUM, "$numfile") or die ("can't open $numfile to read\n");
if (($_ = <NUM>) && (/^([0-9]+)$/)) {
    $slokanum = $1;
}
else {
    die "$numfile bad contents\n";
}
close NUM;

# Scan the Sloka file for the Sloka to post.
$cursloka = "";
open(SLOKA, "$slokafile") or die ("can't open $slokafile\n");
LINE: while (<SLOKA>) {
    if (/^shlokaH[ \t]+([0-9]+)/) {
        my $i = $1;
        next LINE if ($i < $slokanum);

        # can't find the correct sloka? skip to the next higher one.
        if ($i > $slokanum) {
            print "can't find Sloka $slokanum; skipping to Sloka $i instead\n";
            $slokanum = $i;
        }

        # Skip to the Sloka to post.
        if ($i == $slokanum) {
            # extract the Sloka to post from the Sloka file.
            do {
                $cursloka .= $_;
            } until ((! ($_ = <SLOKA>)) || (/^shlokaH[ \t]+([0-9]+)/));
            close SLOKA;
            (system("mail -s \"udyogaparvam - sarga $sarga - $slokanum\" sanskrit\@cs.utah.edu << _EOF_\n\
Translation by Vikram Santurkar under supervision of Dr. Sarasvati Mohan\n\
$cursloka\n\
_EOF_\n") == 0) or print "couldn't send mail\n";

            # Update the current sloka number in the number file.
            ++ $slokanum;
            open(NUM, ">$numfile") or die ("can't open $numfile to write\n");
            print NUM "$slokanum\n";
            close NUM;
            exit 0;
        }
    }
}
close SLOKA;

(system("mail -s \"Admin: udyogaparvam postings\" sai\@cs.utah.edu << _EOF_\n\
All Slokas posted from $slokafile\n\
- Sai's auto-postman.\n\
_EOF_\n") == 0) or print "couldn't send mail\n";
exit 0;
