#!/usr/bin/perl

use strict;

use LWP::UserAgent;
use HTTP::Request::Common;
use HTML::Form;

$| = 1;

sub SPCS_version { '0.02' };

my $ua = LWP::UserAgent->new(
    agent       =>
        'Spamcop submitter v' . SPCS_version .
        ' based on libwww-perl/' . $LWP::VERSION,
    env_proxy   => 1
);

while (<STDIN>) {
    my $string = $_; chomp $string;
    if ($string =~ /^http:\/\/spamcop\.net\/sc\?id=([0-9a-z]{44})$/) {
        print("Submitting $string...");
        my $res = $ua->request(
            GET($string)
        );
        if ($res->is_success) {
            if ($res->as_string =~ /Please wait - subscribe to remove this delay/) {
                print("Delaying...");
                sleep(60);
                redo;
            }
            my @forms = HTML::Form->parse(
                $res->content,
                $string
            );
            unless (defined($forms[0])) {
                print("ERROR\n");
                warn("Can't find any form in HTTP::Response");
                next;
            }
            my $form    = $forms[0];
            my $action  = $form->value('action');
            my $spamid  = $form->value('spamid');
            my $crc     = $form->value('crc');
            my $date    = $form->value('date');
            my $source  = $form->value('source');
            unless (
                defined($action) &&
                defined($spamid) &&
                defined($crc) &&
                defined($date) &&
                defined($source)
            ) {
                print("ERROR\n");
                warn("Can't find mandatory data in HTTP::Response");
                next;
            }
            print("Found $spamid ($crc)...");
            my $res = $ua->request(
                $form->click
            );
            if ($res->is_success) {
                print("Done!\n");
            } else {
                print("ERROR\n");
                warn("Can't LWP::UserAgent->request(): $res->error_as_HTML");
                next;
            }
        } else {
            print("ERROR\n");
            warn("Can't LWP::UserAgent->request(): $res->error_as_HTML");
            next;
        }
    }
}
