#! /usr/bin/perl
#
# Works on perl >= 5.8.3, some trubble with old versions.
#
# Usage:
# Takes argumensts as search-words
# f.x ./getporn.pl blonde stockings
# will give you about 1000 pics, and 700->1000 seems normal with
# two arguments.
# 
# Requires reshane, see http://www.stud.ntnu.no/~shane/stasj/bin-src/
#
# TODO: rewrite all the system-calls and reimplement reshane as a 
# subrutine. 


use warnings;
use strict;                  
use POSIX;

# Some config
my $pages = 5;    # How many pages at xahara to search
my $to = 15;      # Timeout for wget
# End config

my $query = join("+", @ARGV);
#my $search = join("_", @ARGV);
my $site_nr = 1;
my $time = strftime("\%m-\%d-\%Y_\%H-\%M",localtime);
my $resultat = "fangst_$time";
my $temp_dl = "temp_$time";

for (my $page = 1;$page <= $pages; $page++) {
  my $url = "http://www.xahara.com/search.php?preview_images=1&q=$query&page=$page&sm=0&st=0";
  open my $links, "-|", lynx => '-dump', $url; 
  my @links = <$links>;
  close $links;

  foreach my $link (@links) {                       # clean a little.
    $link =~ s/^\ +//g;
    $link =~ s/\d+\.\ //g;
  }
  my @ignore = ('(?!.*xahara)',                     # No-good linkes. Just add.
                '(?!.*adultfriendfinder)',
                '(?!.*asacp)');
  my $ignore = join("", @ignore);

  my @hit = sort(grep /^http$ignore/ ,@links);      # Only lines with http 
  my %seen = ();                                    # 
  my @hits = grep { ! $seen{$_} ++ } @hit;          # kill dupes in array.

  foreach my $thumb_side (@hits) {
    chomp($thumb_side);
    system("mkdir $temp_dl $site_nr $resultat;");
    system("wget -T $to -P $temp_dl/ -r -l 2 -np -R \*.htm\*,\*.txt,\*.css -A \*.jpg --referer=$thumb_side $thumb_side;");
    system("find $temp_dl -iname \*.jpg -exec mv \'{}\' $site_nr \\;");
    system("rm -rf $temp_dl;");
    system("find $site_nr -type f -size -10k -exec rm \'{}\' \\;");
    system("find $site_nr -type f -iname \*_tn\* -exec rm \'{}\' \\;");
    system("find $site_nr -type f -iname \*thumb\* -exec rm \'{}\' \\;");
    system("reshane $site_nr;mv $site_nr/\* $resultat;rmdir $site_nr\n");
    $site_nr++
  }	
}




