#! /usr/bin/perl -w
#
#	Original script: http://mordred.ao.com/rootwindow/
#
#	Create a csv file of all of the Astronomy Picture of the Day
#	images from the start until present.
#
#	This is typically called out from the user's crontab with something like:
#	    30 5 * * * .../randastro ~/.rootwindow/randastro2.csv
#

use strict;
use LWP::Simple;

use vars qw($BaseURL @Csv $NFetch $SYear $SMon $SDay $Version);

$BaseURL = 'http://antwrp.gsfc.nasa.gov/apod';
$Version = 'randastro v0.01 regan@ao.com';

$SYear	= 1995;
$SMon	=    6;
$SDay	=   15;
$NFetch =   11111111;

### CSV Format
###   Year,Month,Day,HTML_URL,IMG_URL
###    0    1     2   3        4

###
###	Main program
###

    my($day, $day2, $fetch, @fields, $mon, $mon2, @montab, @tm,
    		$urlhtml, $year, $year2);

    if (!defined($ARGV[0]))
    	{
	print "Usage: $0 file.csv\n";
	exit 1;
	}
    if (open(CSV, "<$ARGV[0]"))
    	{
	    while (<CSV>)
	    {
		chomp;
		@fields = split(',', $_);
		if (&date_cmp(($SYear, $SMon, $SDay),
			      ($fields[0], $fields[1], $fields[2])) < 0)
		    {
			$SYear = $fields[0];
			$SMon = $fields[1];
			$SDay = $fields[2];
		    }
		}
	    close CSV;
	}

    # Cycle through all possible URLs
    @montab = qw(31 28 31 30 31 30 31 31 30 31 30 31);

    open(CSV, ">>$ARGV[0]") || die "Cannot open $ARGV[0] for write: $!";
    @tm = localtime();
    $fetch = 0;
    for ($year = $SYear ; $year <= ($tm[5]+1900) && $fetch < $NFetch ; $year++)
    	{
	$montab[1] = (($year % 4) == 0) ? 29 : 28;
	for ($mon = 1; $mon <= 12; $mon++)
	    {
	    for ($day = 1; $day <= 31 && $fetch < $NFetch; $day++)
	    	{
		# If this isn't a valid day, recycle
		last if ($day > $montab[$mon-1]);

		# If this is >= today, we quit
		if (&date_cmp(($year,$mon,$day),
			      ($tm[5]+1900, $tm[4]+1, $tm[3])) > 0)
		{
		    $fetch = $NFetch;
		    next;
		}

		next if (&date_cmp(($year,$mon,$day),
				   ($SYear, $SMon, $SDay)) <= 0);

		$urlhtml = sprintf "$BaseURL/ap%02d%02d%02d.html",
						$year % 100, $mon, $day;
		my $img = NewImage($urlhtml);
		printf CSV "$year,$mon,$day,$urlhtml,$img\n"
		    if ($img ne "");
		$fetch++;
		}
	    }
	}
    close CSV;


sub date_cmp
{
    my ($y1, $m1, $d1, $y2, $m2, $d2) = @_;

    if ($y1 != $y2)
    { $_ = ($y1 - $y2); }
    elsif ($m1 != $m2)
    { $_ = ($m1 - $m2); }
    else
    { $_ = ($d1 - $d2); }
}


###
###	NewImage
###
###	Get a new image file based upon the URL.
###
sub NewImage
    {
    my($url) = @_;
    my($data, $newurl);

    print "Fetch $url\n";
    sleep(rand(5));
    $data = get($url);
    if (defined($data) && length($data) > 0 &&
    		$data =~ /img src\s*=\s*"(.*?)"/im)
    	{
	$newurl = "$BaseURL/$1";
	print "Url is $newurl\n";
	return $newurl;
	}
    return "";
    }
