#!/usr/bin/perl

use strict;
use warnings;
use Time::HiRes qw( gettimeofday );
use WWW::Mechanize;
use Data::Dumper;

# 2011-09-13 (ed)
# 	script to confirm the report at spamcop
		
my %config = (
	user => '',
	pass => '',
	history => $ENV{'HOME'} . "/.spamcop/history",
	history_tmp => $ENV{'HOME'} . "/.spamcop/history.$$",
	log_file => $ENV{'HOME'} . "/.spamcop/log",
	sc_url => qr|^(http://www.spamcop.net/sc\?id=z\S+)$|,
);

my %history;

sub log_entry {
	my $f = shift;
	my @t = localtime();
	eval {
		open( LOG, ">>" . $config{'log_file'} );
		printf( LOG "%.4d%.2d%.2d-%.2d%.2d%.2d [%d] %s\n", $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], $$, $f );
		close( LOG );
	};
	if( $@ ) {
		print STDERR "Error writing to log file: $!\n";
	}		
}

sub store_page {
	my $namespace = shift;
	my $content = shift;
	my @t = localtime();
	my $path = sprintf( "/tmp/%s-%.4d%.2d%.2d-%.2d%.2d%.2d.%.06d-spam", 
		$namespace,
		$t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], (gettimeofday())[1] );

	print $path, "\n";

	eval {
		open( F, ">$path" );
		print F $content;
		close(F);
	};
}

sub store_history {
	log_entry( "Storing history..." );
	eval {
		open( F, ">${config{'history_tmp'}}" );
		foreach( keys %history ) {
			print F $_, "\n";
		}
		close(F);
		log_entry( "Finsihed storing history" );
	};
	if( $@ ) {
		log_entry( "Error storing history:$!" );
	}
}

sub load_history {
	log_entry( "loading history" );
	if( ! -f ${config{'history'}} ) {
		log_entry( "history file does not exist" );
		return;
	}
	open( F, "<${config{'history'}}" );
	while( my $line = <F> ) {
		chomp $line;
		if( $line =~ $config{'sc_url'} ) {
			$history{$line} = 1;
		}
	}
	close(F);
	log_entry( "finished loading history" );
}

sub submit {
	my $url = shift;
	my $mech = WWW::Mechanize->new;
	$mech->get( $url );
	store_page( "spamcop", $mech->content );

	$mech->form_name("sendreport");
	log_entry( "sending click..." );
	my $response = $mech->click();

	if( $response->is_success ) {
		log_entry( "Status: " . $response->status_line );
		store_page( "spamcop", $response->decoded_content );
		$history{$url} = 1;
	}
	else {
		log_entry( "There was an error: " . $response->status_line );
		store_page( $response->decoded_content );
	}
}

sub main {
	log_entry( "Starting up" );
	load_history();
	if( defined( $ARGV[0] ) && $ARGV[0] eq "-" ) {
		while( <STDIN> ) {
			if( $_ =~ $config{'sc_url'} 
					&& !defined( $history{$1} )) {
				log_entry( "Processing $1" );
				eval {
					submit( $1 );
				};
				if( $@ ) {
					log_entry( "Error procesing $1" );
					delete( $history{$1} );
				}
			}
		}
	}
	else {
		foreach my $url ( @ARGV ) {
			log_entry( "Processing $url" );
			next if( defined( $history{$url} ) );
			eval { 
				submit( $url );
			};
			if( $@ ) {
				log_entry( "Error procesing $url" );
				delete( $history{$url} );
			}
		}
	}
	store_history;
	log_entry( "Exiting normally" );
}

main;

