#!/usr/bin/perl -w

use strict;

use CGI qw(:standard);

use LWP::UserAgent;
use HTTP::Response;
use HTTP::Request;

my $url = "http://www.animenfo.com/search.php";

my $ua = LWP::UserAgent->new(agent => "Dave's Crazy AnimeNfo Search Interface");

my $anime;

my $response;
my $return;

my @urls;
my $badwords = "JavaScript|helpabout";

sub fetch {
	$response = $ua->post($url, { query => $anime, queryin => "anime_titles", option => "smart" });
	if ($response->is_success) {
		$return = $response->content;
		$return =~ s/.*Search Result//s;
		@urls = grep {!/$badwords/o} $return =~ /href=["']([^"']+)["']/g;
		if (@urls) {
			$return = "http://www.animenfo.com/$urls[0]";
			return 1;
		} else {
			return 0;
		}
	} else {
		return -1;
	}
}

if (defined(param("anime"))) {
	$anime = param("anime");
	if (&fetch == 1) {
		print "Content-type:text/html\nStatus: 303 See Other\nLocation: $return\n\n";
	} elsif (&fetch == 0) {
		print "Content-type:text/html\nStatus: 303 See Other\nLocation: $url\n\n";
	} else {
		print "Content-type:text/html\n\n";
		print "Apologies, but I couldn't reach or understand $url\n";
	}
} else {
	$anime = join(' ', @ARGV);
	if (&fetch == 1) {
		print "First match for ($anime): $return\n";
	} elsif (&fetch == 0) {
		print "No matching search results for ($anime)\n";
	} else {
		print "Apologies, but I couldn't reach or understand $url\n";
	}
}
