#!/usr/bin/perl

use strict;

#use Win32::GUI; BEGIN {Win32::GUI::Hide(scalar(Win32::GUI::GetPerlWindow()))};  # hide the console

use LWP::Simple qw/$ua/;
use File::Spec::Functions;


my ($server, $palmdir) = @ARGV;  # arguments: download-server, local palm-directory
$server ||= 'hawaii.uxi.nl';
$palmdir ||= 'C:\agb\Palm\agb';
my $repeat = 5*60;  # repeat after 5 minutes


my $dlurl = "http://$server/palm/";  # append the filename to download

my $dldir = catfile $palmdir, 'Install_download';
mkdir $dldir unless -e $dldir;
my $instdir = catfile $palmdir, 'Install';


LWP::Simple::_init_ua;
# [No proxy here]$ua->proxy(["http", "ftp"], "http://www-proxy.ericsson.se:80");
sub initagent { $ua->agent("Mozilla/4.0." . int rand 2000); }

sub get
{
	my ($url) = @_;

	my $content;

	print "Downloading '$url'\n";
	my $request = HTTP::Request->new(GET => $url);
	# (don't do this, because it will not work if this clock is ahead of the server's clock)$request->headers->if_modified_since(time);
	my $response = $ua->request($request);
	if ($response->is_success)
	{
		$content = $response->content;
	}
	elsif ($response->status_line)
	{
		print "URL: $url\n";
		(my $error = $response->status_line) =~ s/[\r\n]+/\n/g;
		#print "HTTP ERROR: " . $response->error_as_HTML . "\n";
		print "HTTP ERROR: $error\n";
	}
	else
	{
		print "URL: $url\n";
		print "UNKNOWN HTTP ERROR\n";
		print "HTTP ERROR: " . $response->as_string . "\n";
	}

	return $content;
}

sub save
{
	my ($content, $fname) = @_;

	open FILE, "> $fname" or die "Cannot open '$fname': $!";
	print "Saving '$fname'\n";
	binmode FILE;
	print FILE $content;
	close FILE;
}


sub update
{
	# Get the list with files
	my $list = get $dlurl;
	unless ($list)
	{
		print "Could not download list\n";
		return;
	}
	my %files;
	foreach (split /[\r\n]+/, $list)
	{
		if (my ($age, $fname) = /([.\d]+)\t(.*)/)
		{
			$files{$fname} = $age;
		}
	}

	# Go through the list and check which files should be updated
	foreach (sort keys %files)
	{
		my $dlfile = catfile $dldir, $_;
		my $age = time() - (stat $dlfile)[9];
		if (!-e $dlfile || $age > $files{$_})
		{
			# This file doesn't exist or it is older.
			my $content = get "$dlurl$_";
			next unless defined $content;  # don't save erroneous files
			my $instfile = catfile $instdir, $_;  # file in the 
			save $content, $dlfile;
			(my $install = $palmdir) =~ s/[^\\\/]+[\\\/]?$/Instapp.exe/;  # this is the install application
			if (!-e $instfile && -e $install)
			{
				# File doesn't yet exist and we have an installer,
				# start the installer in a separate process, so that it doesn't block further checking.
				if (fork == 0)
				{
					# This is the child process
					system $install, $dlfile;
					exit;  # end this process
				}
			}
			else
			{
				# Do not install file. Update it in the directory
				save $content, $instfile;
			}
		}
	}

	# Go through all files and delete the ones that are not available anymore
	chdir $dldir;
	foreach (glob '*')
	{
		if (!$files{$_})
		{
			print "Deleting '$_'\n";
			unlink $_;
		}
	}

	print "Updated '$palmdir'\n";
}

while (1)
{
	update;
	last unless $repeat;
	sleep $repeat;
}

