#!/usr/bin/perl

# http://glob.com.au/windowsupdate_cache
# byron jones
# public domain

#
# downloads stuff.  called from redir.pl
#

use strict;

my $cache_path	= '/usr/local/apache/htdocs/cache/store';
my $nice	= '/bin/nice';
my $wget	= '/usr/bin/wget';

my $url = shift;
$url =~ s|^http://||i;
$url =~ s|^www\.||i;
$url =~ s|\?$||;
$url =~ s|//|/|g;

my $debug = shift;

exit if $url =~ /^.*\.asp\?.*$/i;
#logloglog("downloading $url");

aieee("$url exists") if -e "$cache_path/$url";
aieee("$url.downloading exists") if -e "$cache_path/$url.downloading";

chdir($cache_path) || aieee("counld't chdir to $cache_path : $!");

open(FH, '/bin/df .|') || aieee("couldn't run /bin/df : $!");
my $free = 100;
while(<FH>) {
	next unless /\d+\s+(\d+)\%\s+\S+$/;
	$free = $1;
	last;
}
close FH;
aieee("the disk is >90% full") if $free >= 90;

my @paths = split /\//, $url;
my $file = pop @paths;
foreach my $dir (@paths) {
	(-e $dir) || (mkdir($dir, 0755) || aieee("couldn't mkdir $dir : $!"));
	chdir $dir || aieee("couldn't chdir to $dir : $!");
}
open(FH, ">$file.downloading") || aieee("couldn't create $file.downloading : $!");
close FH;
if($debug) {
	system "$nice $wget -nc $url";
} else {
	system "$nice $wget -q -nc $url";
}

unlink "$file.downloading";
exit unless -e $file;

my $size = -s $file;
logloglog("downloaded $size $url");

sub aieee($) {
	my $error = shift;
	logloglog($error);
	exit;
}

sub logloglog($) {
	open(FH, ">>$cache_path/../log");
	print FH '[', scalar localtime, '] ';
	print FH "@_\n";
	close FH;
}
	

