#!/usr/bin/perl -w 

use strict;
use English;

use lib '/home/bdc/tcc/bin';
use BDC ();

use CGI::Pretty ();
use File::Basename ();
use Image::Size ();

BEGIN {
    # uncomment for debugging strange parsing problems with Carp/Heavy/pm
    BDC::clearDieHandlers();
}

my $OptionVerbose = BDC::FALSE();
my $OptionClean = BDC::FALSE();

my $OptionCopy  = BDC::TRUE();
my $OptionGraph = BDC::TRUE();
my $OptionHTML  = BDC::TRUE();
my $OptionUpload  = BDC::TRUE();

my $PoolDataPrefix    = "pool-data-";
my $PoolDataSuffix    = ".csv";
my $PoolDataPattern   = "$PoolDataPrefix*$PoolDataSuffix";
my $PoolDataDirectory = "/tmp";
my $PoolDataPrefixLen = length($PoolDataPrefix);
my $PoolImageDirectory= "htdocs/pool";
my $PoolImageFormat   = "png";


sub main ()
{
    BDC::chdirOrDie("/home/bdc/carlstrom.com/");
 
    if ($OptionCopy) {
	if ($OptionVerbose) {
	    print("COPYING POOL DATA\n"); 
	}
	BDC::systemOrDie("rsync",
			 "-a",
			 ($OptionVerbose ? ("-v", "-P") : ()),
			 "lilred-wireless:/cygdrive/c/misterhouse/data/$PoolDataPattern",
			 $PoolDataDirectory);
	if ($OptionVerbose) {
	    print("\n");
	}
    }

    my @csvfiles = <$PoolDataDirectory/$PoolDataPattern>;

    if ($OptionGraph) {
	if ($OptionVerbose) {
	    print("GRAPHING\n");
	}
	foreach my $csv (@csvfiles) {
	    my $date = csv2Date($csv);
	    my $poolImageFile = csv2image($csv);
	    if ($OptionVerbose) {
		print("$poolImageFile ");
	    }
	    if (!$OptionClean &&
		-e $poolImageFile && 
		BDC::modificationTime($poolImageFile) > BDC::modificationTime($csv)) 
	    {
		if ($OptionVerbose) {
		    print("skipping\n");
		}
		next;
	    }
	    if ($OptionVerbose) {
		print("generating\n");
	    }
	    BDC::removeFileOrDie($poolImageFile);
	    # based on
	    # chron example 7 - hourly temperature readings plotted for one week
	    # http://ploticus.sourceforge.net/doc/prefab_chron_ex.html
	    BDC::systemOrDie("ploticus",
			     "pool.ploticus",
			     ($OptionVerbose ? ("-debug", "-echo", "echodata=yes") : ()),
			     "data=$csv",
			     "date=$date",
			     "-$PoolImageFormat",
			     "-o", $poolImageFile);
	}
	if ($OptionVerbose) {
	    print("\n");
	}
    }
    
    if ($OptionHTML) {
	if ($OptionVerbose) {
	    print("HTML\n");
	}
	for (my $i = 0; $i < @csvfiles; $i++) {
	    my $csv = $csvfiles[$i];
	    my $date = csv2Date($csv);
	    my $poolHTMLFile  = csv2html($csv);
	    my $poolImageFile = csv2image($csv);
	    if ($OptionVerbose) {
		print("$poolHTMLFile ");
	    }
	    if (! -e $poolImageFile) {
		if ($OptionVerbose) {
		    print("could not find $poolImageFile\n");
		}
		next;
	    }

	    my $c = new CGI::Pretty();
	    my $nav = ($c->start_p().
		       $c->start_center());
	    if ($i != 0) {
		my $prevCSV = $csvfiles[$i-1];
		my $prevDate = csv2Date($prevCSV);
		my $prevHTML = csv2html($prevCSV, BDC::TRUE());
		$nav .= $c->a({href=>$prevHTML}, "< $prevDate");
	    }
	    if ($i != 0 && $i != @csvfiles-1) {
		$nav .= " | ";
	    }
	    if ($i != @csvfiles-1) {
		my $nextCSV = $csvfiles[$i+1];
		my $nextDate = csv2Date($nextCSV);
		my $nextHTML = csv2html($nextCSV, BDC::TRUE());
		$nav .= $c->a({href=>$nextHTML}, "$nextDate >");

		# if next file does not exist, force regen of current file to make sure nav is correct
		if (! -e csv2html($nextCSV)) {
		    BDC::removeFileOrDie($poolHTMLFile);
		}
	    }
	    $nav .= ($c->end_center().
		     $c->end_p());

	    if (!$OptionClean &&
		-e $poolHTMLFile && 
		BDC::modificationTime($poolHTMLFile) > BDC::modificationTime($csv))
	    {
		if ($OptionVerbose) {
		    print("skipping\n");
		}
		next;
	    }
	    if ($OptionVerbose) {
		print("generating");
	    }
	    my $o = BDC::writeOrDie($poolHTMLFile);
	       
	    $o->print(header("Temperatures for $date"));
	    $o->print($c->a({href=>"compool/"}, "Notes on Pentair Compool Hacking"));
	    $o->print($c->p($c->img({src=>csv2image($csv, BDC::TRUE()), Image::Size::attr_imgsize(csv2image($csv))})));
	    $o->print($nav);
	    $o->print(footer());

	    BDC::closeOrDie($o);
	    
	    if ($i == @csvfiles-1) {
		if ($OptionVerbose) {
		    print(" creating index.html symlink\n");
		}
		my $link = "$PoolImageDirectory/index.html";
		BDC::removeFileOrDie($link);
		BDC::systemOrDie("ln", "-s", csv2html($csv, BDC::TRUE()), $link);
	    }
	    else {
		if ($OptionVerbose) {
		    print("\n");
		}
	    }
	}
	if ($OptionVerbose) {
	    print("\n");
	}
    }

    if ($OptionUpload) {
	if ($OptionVerbose) {
	    print("UPLOADING TO CARLSTROM.COM\n");
	}
	BDC::systemOrDie("rsync",
			 "-a",
			 ($OptionVerbose ? ("-v") : ()),
			 "htdocs/pool/",
			 "electricrain.com:www/htdocs/pool/");
	if ($OptionVerbose) {
	    print("\n");
	}
    }
}

sub csv2Date ($)
{
    my ($csv) = @_;
    my $basename = File::Basename::basename($csv, $PoolDataSuffix);
    my $date = substr($basename, $PoolDataPrefixLen);
    return $date;
}

sub csv2image ($@)
{
    my ($csv, $short) = @_;
    my $basename = File::Basename::basename($csv, $PoolDataSuffix);
    my $filename = "$basename.$PoolImageFormat";
    if ($short) {
	return $filename;
    }
    return "$PoolImageDirectory/$filename";
}

sub csv2html ($)
{
    my ($csv, $short) = @_;
    my $basename = File::Basename::basename($csv, $PoolDataSuffix);
    my $filename = "$basename.html";
    if ($short) {
	return $filename;
    }
    return "$PoolImageDirectory/$filename";
}

sub header ($$)
{
    my ($page) = @_;

    return <<"EOF"
<?php
  require_once('../../php/sections.php');
  \$section = \$SectionProjects;
  \$subsection  = "Pool";
  \$title       = "$page";
  require_once('../../php/header.php');
?>
EOF
;
}

sub footer ()
{   
    return <<'EOF'
<?php require_once('../../php/footer.php') ?>
EOF
;
}   
main();

