#!/usr/bin/perl

# Look at */html/tmp starting from ARGV[0] if it exists
# Otherwise start at hardwired value

# For each, if directory, recurse down
# If file, check access time, if > delay, remove

$delay = 777600; # in seconds
$home = '/ud/webwork/base/courses';

$timenow = time();
$old = $timenow-$delay;

if(@ARGV>0) { $home = $ARGV[0]; }

sub get_files {
	my $start = shift;
	opendir STDIR, $start or die "Cannot open directory $start";
	my @allfiles = grep !/^\.\.?/, readdir STDIR;
	closedir(STDIR);
	@allfiles;
}

sub find_html {
	my $start = shift;

	my @alldirs = get_files($start);
	my $j;
	for $j (@alldirs) {
		if(-d "$start/$j") {
			if("$j" eq "html") {
				find_tmp("$start/$j");
			} else {
				find_html("$start/$j");
			}
		}
	}
}

sub find_tmp {
	my $start = shift;
	
	my @alldirs = get_files($start);
	my $j;
	for $j (@alldirs) {
		if(-d "$start/$j") {
			if("$j" eq "tmp") {
				clean("$start/$j");
			}
		}
	}
}

# Take a directory and recursively search
# If it is a directory, go into it
# If it is a file, check mod time and maybe remove it
sub clean {
	my $start = shift;
	my @alldirs = get_files($start);
	my $j;
	for $j (@alldirs) {
		my @stat_info = stat "$start/$j";
		if(-d _) {
			clean("$start/$j");
		} else {
			if($stat_info[8]<$old) {
# print "Trying to remove $start/$j\n";
				unlink("$start/$j") or print("*** Cannot remove $start/$j\n");
			}
		}
	}
}

find_html($home);
