#!/usr/bin/perl

local $pak = '';
local $DEP = ();
local $URL = ();
local $NYL = ();
local $GET = ();

# http://ftp.de.debian.org/debian/dists/etch/main/binary-mipsel/Packages.gz
# ->
# http://ftp.de.debian.org/debian/pool/main/l/lighttpd/lighttpd_1.4.13-4etch4_mipsel.deb

local $FEEDS = "cat feed/Packages;cat ../nylon/Packages;zcat ../meshcube.org/nylon/stable/binary-feed/Packages.gz;zcat ../meshcube.org/nylon/stable/feed/Packages.gz";
if ($#ARGV >= 0 && $ARGV[0] eq "-d")
{
	shift(@ARGV);
	$FEEDS = "cat feed/Packages";
}

foreach(`$FEEDS`)
{
	chomp;
	if (m#^Package:\s+#s)
	{
		$pak = $';
	}
	elsif (m#^Filename:\s+#s)
	{
		$NYL{$pak} = $';
	}
}

foreach(`zcat Debian-Etch-Mipsel.gz`)
{
	chomp;
	if (m#^Package:\s+#s)
	{
		$pak = $';
	}
	elsif (m#^Filename:\s+#s)
	{
		$URL{$pak} = $';
	}
	elsif (m#^Depends:\s+#s)
	{
		$DEP{$pak} = $';
	}
}

sub collect($)
{
	my $p = shift;
	if (defined($URL{$_}))
	{
		if (!defined($NYL{$_}))
		{
			$GET{$_} = 1;
			foreach(split(/\,/, $DEP{$_}))
			{
				s/^\s+//;
				s/\s+.*//;
				collect($_) if (!defined($GET{$_}));
			}
		}
	}
	else
	{
		print STDERR "No such packet: $p\n";
	}
}

foreach(@ARGV)
{
	collect($_);
}

foreach(sort keys %GET)
{
	print "wget -c http://ftp.de.debian.org/debian/$URL{$_}\n";
	system("cd feed && wget -c http://ftp.de.debian.org/debian/$URL{$_}");
}
