#!/usr/bin/perl

# addreading
# ----------
# Takes zero to four arguments
#   A bible-id, from first column of urls.txt. Defaults to 'bgniv'.
#   A plan-id, from the first column of plans.txt. Defaults to 'ttb'.
#   A date in mm-dd format.  Defaults to current date (or use 00-00).
#   The file to update. Defaults to $1-$2.xml
# ----------

use POSIX qw(strftime);
use File::Basename qw(basename dirname);
use File::Copy qw(copy);

sub countlines
{
    # input: handle to an open file
    # returns: number of lines

    my $fh = shift;
    my $numlines;

    seek($fh, 0, 0);
    $numlines = 0;
    while( <$fh> )
    {
    	++$numlines;
    }
    return $numlines;
}

sub emitlines
{
    # input: handle IN, handle OUT,  startline, endline
    # returns: nothing

    my ($inf, $outf, $first, $last) = @_;
    my $linecount;

    $linecount = 0;
    seek($inf, 0, 0);

    while( <$inf> )
    {
    	++$linecount;
    	if( $linecount >= $first && $linecount <= $last )
    	{
    		print $outf  $_;
    	}
    }
}

sub awkit
{
    # input: handle IN, string to match, field separator, field to return 
    my ($inf, $match, $fs, $fi) = @_;
    seek($inf, 0, 0);
    while( <$inf> )
    {
    	if( /$match/ )
    	{
    		@a = split(/$fs/, $_);
    		last;
    	}
    }
    chomp( $ret = $a[$fi] );
    return $ret;
}

sub fmtdate 
{
    # fmtdate $fmt
    if( @_ == 1 )
    {
    	return strftime( $_[0], localtime ); 
    }

    # fmtdate $fmt, $sec, $min, $hr, $day, $mon, $yr
    else
    {
    	@t = @_;
    	$fmt = shift(@t);
    	return strftime( $fmt, @t );
    }
}

sub convmd
{
    # args: date in %m-%d format
    # returns: date in gmtime list format

    @d = split(/-/, $_[0]);
    @d = reverse(@d);
    unshift(@d, 0,0,0);
    push(@d, strftime("%Y", localtime));
    @d[4] -= 1;
    @d[5] -= 1900;

    return @d;
}

# set working directory
chdir( dirname($0) );

# set any missing arguments

$bibleid = shift (@ARGV);
if( ! $bibleid )  { $bibleid = "bgniv"; }

$planid = shift (@ARGV);
if( ! $planid ) { $planid = "ttb"; }

$readdate = shift (@ARGV);
if( ! $readdate || $readdate eq '00-00' )  { $readdate = fmtdate("%m-%d"); }

$outfile = shift (@ARGV);
if( ! $outfile )  { $outfile = $bibleid . '-' . $planid . ".xml"; }

# start with template file if output file doesn't exist

if ( ! -e $outfile )
{
    copy("template.txt", $outfile) or die "Copy failed: $!";
}

open (RD, "plans.txt") or die "Couldn't open plans.txt for reading: $!";
$planfile = awkit( \*RD, $planid, ":", 1);
$plantitle = awkit( \*RD, $planid, ":", 2);
close(RD);

open (RD, "urls.txt") or die "Couldn't open urls.txt for reading: $!";
$biblever = awkit( \*RD, $bibleid, " ", 1);
close(RD);

# header
$tmpfile = "tmp1";
open (IN, $outfile) or die "Couldn't open $outfile for reading: $!";
open (OUT, ">$tmpfile") or die "Couldn't open $tmpfile for writing: $!";

emitlines(\*IN, \*OUT, 1, 4);

# title (channel)
print OUT "<title>" . $plantitle . " (" . $biblever .")</title>\n";

emitlines(\*IN, \*OUT, 6, 7);

# lastBuildDate
print OUT "<lastBuildDate>" . fmtdate("%a, %d %b %Y %H:%M:%S GMT", gmtime) . "</lastBuildDate>\n";

# atom feed
$o = basename($outfile);

seek(IN, 0, 0);
while( <IN> )
{
    if( /atom:/ )
    {
    	$line = $_;
    	last;
    }
}
$line =~ s/__bver__/$o/;
print OUT $line;

# open item
print OUT "\n<item>\n";

# title
open(RD, $planfile) or die "couldn't open readings file: $!";
$t = awkit (\*RD, $readdate, "=", 1 );
print OUT "<title>$t</title>\n";
close(RD);
if( substr($t, 0, 1) eq "(" ) { $t = "" }

# description
@d = convmd($readdate);
print OUT "<description>" . fmtdate("Reading for %a, %d %b", @d) . "</description>\n";

# link
open(RD, "urls.txt") or die "couldn't open urls.txt: $!";
$s = awkit (\*RD, $bibleid, " ", 2 );
$t =~ tr/ /+/;
print OUT "<link>$s$t</link>\n";
close(RD);

# pubDate
print OUT "<pubDate>" . fmtdate("%a, %d %b %Y %H:%M:%S GMT", gmtime) . "</pubDate>\n";

# guid
print OUT "<guid>$s$t</guid>\n";

# close item
print OUT "</item>\n";

# remainder of file, limit to $n items (including the new one)
$n = 5;
$numlines = countlines(\*IN);
if( $numlines < (10+8*$n+2) )
{
    emitlines( \*IN, \*OUT, 10, $numlines );
}
else
{
    emitlines( \*IN, \*OUT, 10, (10+($n-1)*8) );
    emitlines( \*IN, \*OUT, $numlines-1, $numlines );
}

close(IN);
close(OUT);

copy($tmpfile, $outfile) or die "Copy failed: $!";
unlink($tmpfile) or die "Couldn't unlink $tmpfile: $!";

# end
