#!/usr/athena/bin/perl -T

require 5.002;
use strict;
use Socket;

my $umhostname = "umweb1.unitedmedia.com";

#
# Gets the contents of the file passed as an argument 
#
sub get_page_contents
{
    my ($path,$printonreceive) = @_;

    my ($remote, $port, $iaddr, $paddr, $proto, $line);
    
    $remote = $umhostname;
    $port = 80;
    $iaddr = inet_aton($remote)                or die "no host: $remote";
    $paddr = sockaddr_in($port, $iaddr);
    
    $proto = getprotobyname("tcp");
    socket(SOCK, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
    connect(SOCK, $paddr)                      or die "connect: $!";

    select((select(SOCK), $| = 1)[0]); # Make unbuffered
    print SOCK "GET ".$path."\n" or die "error sending query: $!";

    select(SOCK); $|=1; select(STDOUT);

    if ($printonreceive)
    {
	while (<SOCK>) { print; }
	close(SOCK) or die "close: $!";
    }
    else
    {
	my @contents = <SOCK>;
	close(SOCK) or die "close: $!";
	return @contents;	
    }
}


sub get_gif_name
{
    my ($comicname, $datestr) = @_;
    my $pagename;

    if ($datestr =~ /\d\d\d\d\d\d/)
    {
	$pagename = 
	    "/comics/".$comicname."/archive/".$comicname.$datestr.".html";
    }
    elsif ($datestr =~ /today/)
    {
	$pagename = "/comics/".$comicname."/archive/";
    }
    elsif ($datestr =~ /sunday/)
    {
	$pagename = "/comics/".$comicname."/archive/latest_sunday.html";
    }
    else
    {
	die "invalid date (must be YYMMDD or \"today\") and is ".$datestr;
    }

    #print "going to ".$pagename."\n";
    my @contents = get_page_contents ( $pagename, 0 );
    #print "CONTENTS: ".(join "",@contents)."\n----------------\n";

    my @gifline = grep m:<IMG SRC=\"/comics/[a-z0-9A-Z]+/archive/images/:, @contents
	or die "image not found in file";  # "
    #print "LINE: <".$gifline[0].">\n";
    $gifline[0] =~ m:<A HREF=\"(.*)\"> <IMG SRC=:;   # "
    return $1;
    #print $1."\n";
}

print "Content-type: image/gif\n\n";
#print "ARGV is ".@ARGV."\n";

if (@ARGV != 2)
{
    die "Invalid usage";
}

my @theimage = get_page_contents(get_gif_name ($ARGV[0], $ARGV[1]),1);
#print "FILENAME: <".(get_gif_name ($ARGV[0], $ARGV[1])).">\n";
#foreach (@theimage) { print $_ ;}
