#!/usr/bin/perl

my $VERSION = "v0.1";
#CREDIT AND CONTACT:
#		This script written by derMoerder. You may contact me via ICQ @ 23115071, or just find me on the SomethinAwful forums(or DPPHv2) as derMoerder.
#		derM@eden.rutgers.edu
#

use strict;
use Getopt::Std;
use vars qw( $opt_c $opt_e ); #c is cutoff size in kilobytes, e is extension-type deleted

my $icDeleted = 0;

main();


sub main {
	my %optDef = (	c => 2, #default size in kilobytes
					e => '' ); #default extension-type deleted is null string to signify 'any'

	if( $#ARGV < 0 || ( $ARGV[ $#ARGV ] eq "--help" ) ) { #check for version or help options
		PrintHelp();
	}#end if				

	getopts( 'c:e:' );
			#if the key wasn't given a value on the command-line, we'll set it to default
	if( $opt_c eq '' ) { $opt_c = $optDef{ 'c' }; }
	if( $opt_e eq '' ) { $opt_e = $optDef{ 'e' }; }

	

	TestAndDelete( $ARGV[ $#ARGV ] );

	print "\n\n$icDeleted files removed. Done.\n";
}

sub TestAndDelete {
	my @sFiles;	#array to hold filenames returned from opendir()
	my $sFile;		#for use in the @sFiles foreach
	my @fileStats;


	opendir( CURDIR, $_[ 0 ] ) || die( "Couldn't open directory  \"$_[ 0 ]\". Dying.\n" );
	@sFiles = sort readdir( CURDIR );	#get filelist from open dir
	closedir( CURDIR );

	foreach $sFile( @sFiles) {
		if( ( $sFile ne "." ) && ( $sFile ne ".." ) ) {
			if( ( -d "$_[ 0 ]/$sFile" ) ) {	#if current file is a dir..
				print "Recursing to \"$_[ 0 ]/$sFile\"\n";
				TestAndDelete( "@_[ 0 ]/$sFile" );
			} else {
				@fileStats = stat( "$_[ 0 ]/$sFile" );
				if( ( $fileStats[ 7 ] < ( $opt_c * 1024 ) ) && ( $sFile =~ m/$opt_e$/ ) ) {
					print "\"$_[ 0 ]/$sFile\" is less than $opt_c KB, removing..\n";
					unlink( "$_[ 0 ]/$sFile" );
					$icDeleted++;
				}#if
			}#if/else
		}
	}#foreach
}#TestAndDelete


sub PrintHelp() {
		print "Usage: killfiles [OPTIONS]... [DIRECTORY]...\n";
		print "Delete files under a certain size in a directory tree.\n\n";

		print "  --help\tPrint this help and exit.\n";

		print "  -c\t\tInt for max cutoff size in deletions, in KB. Default is 2.\n";

		print "  -e\t\tString for the extension type to delete. Deletes any type\n";
		print "\t\tby default. You'll need to specify the extension including\n";
		print "\t\tthe '.' character.\n";

		print "\nkillfiles by derMoerder, $VERSION. Report bugs to derM\@eden.rutgers.edu.\n";
		exit();
}