#!/usr/bin/perl

#Current version: v0.2
#	Changes since last version:
#		--Whoops, forgot a semicolon. :)
#		--Changed the fake referrer - should work on more sites now. It was
#			the directory of the file we want to retrieve, but on the advice of
#			JesusSavesPorn I changed it to send the full path including the
#			file we want to retrieve.
#
#CREDIT AND CONTACT:
#		This script written by derMoerder. You may contact me via ICQ @ 23115071, or just find me on the SA forums(or DPPH) as derMoerder.
#
#NOTE:
#		This script will assume you have wget in your path, or in the same directory as this script. 
#		Filesize cutoff is at 3KB.. anything smaller will be deleted. Feel free to change the constant in the code as you please.
#

@splitCode;
$argv = $ARGV[ $#ARGV ];
$rdir, $files;	#when we break up the EZCode part of the url.. these are the key parts
$fileBeg, $fileEnd;
$startNum, $endNum;
$bShowPadding = 0; #necessary because of some software/people that put 0's as padding in lower numbers.. ala 015.jpg
$target, $fileName;
@numTemp1, @numTemp2;

if( $#ARGV < 0 ) { #no arguments.. just print help.
	print "Usage: EZPicspl [OPTION]... [EZCODE]...\n";
	print "There are no options yet, but you know.. just in case. :).\n";
	print "EZPicspl by derMoerder. v0.1.\n";
	exit();
}


$argv =~ m|^((\w)*://(.*)(?=/)*)/([^/]+)$|;	#so... $1 will be the url with path up to the filenames, and $4 will be the ezcoded filename part(filestart.ext?fileend.ext?name).
$rdir = $1; $files = $4;

@splitCode = split( /\?/, $files ); #split the code into startfile[0] endfile[1] and subdir[2]

( $fileBeg, $startNum, $fileEnd ) = split( /(\d+)/, $splitCode[ 0 ] );
$splitCode[ 1 ] =~ m/[^\d]*(\d+)+[^\d]*/;
$endNum = $1;

if( substr( $startNum, 0, 1 ) eq "0" ) { #if there's padding in the start, we're gonna need to pad whenever the filenum is of less digits than the ending num
	$bShowPadding = 1;
}

for( $i=$startNum+0; $i<$endNum + 1; $i++ ) {	#the +0 is on the $startNum so that it's treated as an integer with any 0-padding chopped off
	print "\n######### EZPicspl: Attempting to retrieve pic $i out of $endNum.\n\n";
	$target = ""; $fileName = "";
	$target .= "$rdir/$fileBeg";
	if( $bShowPadding ) {
		@numTemp1 = split( //, $i );
		@numTemp2 = split( //, $endNum );
		for( $k=0; $k<$#numTemp2 - $#numTemp1; $k++ ) {	#won't insert 0s unless padding is necessary
			$target .= '0';
			$fileName .= '0';
		}
	}
	$target .= "$i$fileEnd";
	$fileName .= "$i$fileEnd";
	print `wget -nd -nc --referer=$target --directory-prefix=\"$splitCode[ 2 ]\" --follow-ftp --user-agent=\"Mozilla/4.04 (X11; I; Etch-A-Sketch 5.4)\"  $target`;
	open( NEWFILE, $fileName );
	@crap = stat( NEWFILE );
	close( NEWFILE );
	if( -e $fileName ) {	#check that it exists before deleting :) maybe wget returned a page-less 404 or something.
		if( $crap[ 7 ] < 3072 ) {	#if it's smaller than 3KB, kill it.
			unlink( $fileName );
			print "$fileName was smaller than 3KB, so it was deleted.";
		}
	}
}