#!/usr/bin/perl -w

require LWP::UserAgent;
#require 'cgi_lib.pl';
    
$ua = new LWP::UserAgent;
$followup = new LWP::UserAgent;
$followup->max_size(1024);
$followup->timeout(10);

my %block;
my $good = 0;

&ReadParse(*input);

print "Content-type: text/html\n\n";
print "<html><head><title>free oth search for $input{'query'}</title>\n";
print "</head>\n<body>\n";

my $cnt = 0;
while(&go($input{'query'},$cnt, $input{'verbose'})){
    $cnt += 20;
}

print "found $good files<br /><br />\n";
print "</body></html>\n";

sub parse{
    my $in = $ENV{'QUERY_STRING'};
    my @in = split(/[&;]/,$in);
    return $in[1];
}

sub go{
    my($query,$skip,$verbose) = @_;
    $| = 1;
    
    $query = "http://oth.net/cgi-bin/search?q=" . $query . "&cl=1";
    $query .= "&skip=" . $skip;
    
    $request = new HTTP::Request('GET',$query);
    $fr = new HTTP::Request;

    $response = $ua->request($request);

    if($response->is_success){
	@page = split /\n/, $response->content;
	foreach $line (@page){
	    if($line =~ /Please search for something more specific/i){
		return 0;
	    }
	    if($line =~ /<a href=\'((\S)+)\.mp3\'>/){
		$url = $1;
		$url =~ /ftp:\/\/((\S)+?)\//;
		$host = $1;
		next unless(!$block{$host});
		$url .= ".mp3";
		$fr->method('GET');
		$fr->uri($url);
		my $response = $followup->request($fr);
		if($response->is_success){
		    print "<b><a href=$url>$url</a></b><br />\n";
		    $good++;
		} else {
		    $block{$host} = 1;
		    if($verbose){
			print "<a href=$url>$url</a><br />\n";
		    } else {
			print ".\n";
		    }
		}
	    }
	}
	return 1;
    } else {
	print $response->error_as_HTML;
	return 0;
    }
}

sub ReadParse {
  local (*in) = @_ if @_; 
  local ($i, $key, $val);
  
  # Read in text
  if (&MethGet) {
    $in = $ENV{'QUERY_STRING'};
  } elsif (&MethPost) {
    read(STDIN,$in,$ENV{'CONTENT_LENGTH'});
  }
    
  @in = split(/[&;]/,$in);

  foreach $i (0 .. $#in) {
    # Convert plus's to spaces
#    $in[$i] =~ s/\+/ /g;
    
    # Split into key and value.
    ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.
   
    # Convert %XX from hex numbers to alphanumeric
#    $key =~ s/%(..)/pack("c",hex($1))/ge;
#    $val =~ s/%(..)/pack("c",hex($1))/ge;

    # Associate key and value 
    $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
    $in{$key} .= $val;
    
  }
   
  return scalar(@in);
}

sub MethGet {
  return ($ENV{'REQUEST_METHOD'} eq "GET");
}

sub MethPost {
  return ($ENV{'REQUEST_METHOD'} eq "POST");
}
















