#!/usr/bin/perl

use warnings;
use strict;
use Digest::MD5;
use LWP::Simple;

chdir('snapshots');

my $snaps = get("http://cygwin.com/snapshots/");
unless ($snaps) { die "Unable to get http://cygwin.com/snapshots/\n"; };
my (@snapurls) = $snaps =~ m|<a href="(http://cygwin.com/snapshots/cygwin-inst-.*?)">|g;

unless (@snapurls)
{
	warn "No matches in web page! Dumping snaps.html\n";
	open(SNAPS,'>','snaps.html');
	print SNAPS $snaps;
	close(SNAPS);
	die "Dumped snaps.html, Exiting\n";
};

@snapurls = ($snapurls[0]);
print STDERR join("\n", @snapurls) . "\n\n";
foreach $_ (@snapurls)
{
	my ($snapfile) = $_ =~ m|/([^/]*)$|;
	my ($snappath) = $_ =~ m|^(.*?)[^/]*$|;
	if (-f $snapfile)
	{
		print STDERR "$snapfile already downloaded!\n";
	}
	else
	{
		print STDERR "Downloading $snappath$snapfile... ";
		system('wget',"$snappath$snapfile");
		print STDERR "Done.\n";
	}
}

print STDERR "\n";

my @tarballs = glob('cygwin-inst-*.tar.bz2');
die "No snapshots in dir!\n" unless @tarballs;
while (1 < @tarballs)
{
	$_ = shift @tarballs;
	print STDERR "Removing $_\n";
	unlink $_;
}

# @tarballs = ($tarballs[$#tarballs]);

foreach my $tarball (@tarballs) {
my ($version) = $tarball =~ m/^cygwin-inst-([0-9]{8})\.tar\.bz2$/;
my $size = -s $tarball;

open(TARBALL, '<', $tarball);
my $md5 = Digest::MD5->new;
$md5->addfile(*TARBALL);
close(TARBALL);
my $md5sum = $md5->hexdigest;

open(SETUPINI, '>', 'setup.ini');
# my $time = time();
# my $setup_ini = <<EOT;
# setup-timestamp: $time
# 
# EOT
# print SETUPINI $setup_ini;
# print $setup_ini;

my $setup_ini = <<EOT;
setup-timestamp: 1000000000

@ cygwin
[test]
version: $version
install: $tarball $size $md5sum

EOT

print SETUPINI $setup_ini;
print $setup_ini;

}

close(SETUPINI);


