#!/usr/bin/perl
#
# (C) Martin J. Bligh 2003
# Released under the GPL, version 2

use Getopt::Long;

my $mirror = "ftp://ftp.kernel.org/pub/linux/kernel";
my $local_mirror = "http://kernel.beaverton.ibm.com/mirror";
my $kernelpset;
my $relative;

GetOptions("mirror|m=s" =>		\$mirror,
	   "debug|d"	=>		\$debug,
	   "relative|r"	=>		\$relative,
	   "local|l"	=>		\$local);

($kernelpset, @patches) = @ARGV;

if ($kernelpset eq "") {
	print "Usage: $0 [-m <mirror>] [-r] <kernel-alias>\n";
	exit 1;
}

if ($relative) { 
	$mirror = ""; 
}

if ($local) {
	$mirror = "$local_mirror/kernel";
	$akpm = "$local_mirror/akpm";
	$mbligh = "$local_mirror/mbligh";
} else {
	$akpm = "$mirror/people/akpm/patches";
	$mbligh = "$mirror/people/mbligh";
}

if ( $kernelpset =~ /^(2\.(\d)\.(\d+(\.\d+)?)(-(test|pre|rc)\d+)?)(-(mm|mjb|bk|git)\d+)?$/ ) {
	($kernel, $minor, $maintbug, $bugfix, $extra, $extraop) = 
				($1, $2, $3, $4, $5, $6);
	$bugfix =~ s/\.//;

		# From kernelpset "2.6.8.3-rc1-mm4" we get:
			# $kernel		2.6.8.3-rc1
			# $minor		6
			# $maintbug		8.3
			# $bugfix		3
			# $extra		-rc1
			# $extraop		rc

	if ($debug) {
		print "kernelpset: $kernelpset\n";
		print "kernel: $kernel\n";
		print "minor: $minor\n";
		print "maintbug: $maintbug\n";
		print "bugfix: $bugfix\n";
		print "extra: $extra\n";
		print "extraop $extraop\n";
	}
} else {
	die "Invalid kernel alias: $kernelpset";
}

# Hack any pset off the end, and deal with it as a patch
if ($kernelpset =~ /(-(mm|mjb|bk|git)\d+)$/) {
	($pset, $psettype) = ($1, $2);

	print "Found patchset $pset, type $psettype\n" if ($debug);

	if ($psettype eq "mm") {
		if ($local) {
			$patch = "$akpm/$kernel/$kernelpset/$kernelpset.bz2";
		} else {
			$patch = "$akpm/2.$minor/$kernel/$kernelpset/$kernelpset.bz2";
		}
	} elsif ($psettype eq "mjb") {
		$patch = "$mbligh/$kernel/patch-$kernelpset.bz2";
	} elsif (($psettype eq "bk") || ($psettype eq "git")) {
		$patch = "$mirror/v2.$minor/snapshots/patch-$kernelpset.bz2";
	}
	print "Appending patch: $patch\n" if ($debug);
	unshift @patches, $patch;
}

if ($extraop eq "rc") {
	$kernelurl = "$mirror/v2.$minor/testing/linux-$kernel.tar.bz2";
} elsif ($extraop eq "test") {
	$kernelurl = "$mirror/v2.$minor/pre-releases/linux-$kernel.tar.bz2";
} else {
	$kernelurl = "$mirror/v2.$minor/linux-$kernel.tar.bz2";
}

$patches = join(' ', @patches);

if ($onlyexppatch) {
	print "$kernel $patches\n";
} else {
	print "$kernelurl $patches\n";
}
