#!/usr/bin/perl -wT

# $Log$

use strict;
use CGI;

# User defined settings
my $LOGFILE = '/home/sporadic/projects/elcid/elcid.log';

# Declarations
my $date = '';
my $time = '';
my $name = '';
my $number = '';
my $rawnum = '';
my $u_time = '';
my $l_time = '';
my @rows = '';
my $count = '';

# CGI Declerations
my $q = new CGI;

# Turn off buffering
$| = 1;

# Main shiznit

# If a numner is passed in, jump to the query and exit.
if (($rawnum = $q->param ('num')) =~ /\d{10}/ )  {
	&query_anywho;
	exit 0;
}

open (FILE, $LOGFILE) or 
	die ("Failed to open logfile.");
@rows = <FILE>;
close (FILE);
@rows = reverse (@rows);

&write_header;
while ( $rows[$count] ne '')  {
	($date, $time, $name, $number, $u_time) = split (/,/, $rows[$count]);
	$rawnum = $number;
	$l_time = localtime ($u_time);
	$name =~ s/([A-Z])([A-Z]*)/$1\L$2/g;
	$name =~ s/^O$/Unknown/;
	$name =~ s/^P$/Private/;
        $number =~ s/^O$/Out of Area/g;
        $number =~ s/^P$/Private/g;
	$number =~ s/(\d{3})(\d{3})(\d{4})/\($1\) $2-$3/;
	&write_body;
	$count++;
}
&write_footer;


###################################
#  
#  HTML Header
#
###################################

sub write_header  {
#	print ("Context-type: text/html\n\n");
#	print ("<head><title>Caller ID Log</title></head>\n");
#	print ("<body>\n");
	print $q->header;
	print $q->start_html ('Caller ID Log');
	print ("<h1><code>Caller ID Log</code></h1>\n");
	print ("<table width=100% border=1><tr>\n");
	print ("<th>Name</th><th>Number</th><th>Date / Time</th></tr>\n");
}


###################################
#  
#  HTML Body
#
###################################

sub write_body  {
	print ("<tr>");
	print ("<td>&nbsp;$name</td>");
	print ("<td>&nbsp;");
	if (($rawnum !~ 'O') && ($rawnum !~ 'P'))  {
		print ("<a href=http://www.anywho.com/cgi-bin/htwpq");
		print ("?state=NA&qtype=telb&tel=$rawnum>");
		print ("$number</a></td>");
	}  else  {
		print ("$number</td>");
	}
	print ("<td>&nbsp;$l_time</td>");
	print ("</tr>\n");
}


###################################
#  
#  HTML Footer
#
###################################

sub write_footer  {
	print ("</table>\n");
	print $q->end_html;
}

###################################
#  
#  anywho.com query
#
###################################

sub query_anywho  {
	print $q->header;
	print $q->start_html ("Query anywho.com - $rawnum");
	print $q->startform (-method => 'post',
		-action => 'http://www.anywho.com/cgi-bin/htwpq#top',
		-name => 'reverse');
	print $q->hidden (-name => 'state', -value => 'NA');
	print $q->hidden (-name => 'qtype', -value => 'telb');
	print $q->hidden (-name => 'tel', -value => $rawnum);
	print $q->submit;
	print $q->endform;
	print $q->end_html;
}
