#!/usr/bin/perl
# Outputs a list of udebs to install. Pass it the type of image to build as
# the first parameter, then the kernel flavour, then the major kernel type
# (2.4, 2.6, etc), then the sub architecture (or an empty string if there
# are none) and then the kernel version(s) as the rest of the parameters.
# Reads the lists in pkg-lists.

use warnings;
use strict;

if (int(@ARGV) < 5) {
	die "Usage: $0 type KERNEL_FLAVOUR KERNELMAJOR SUB_ARCH KERNEL_VERSION [KERNEL_VERSION ...]\n";
}
my $type=shift;
my $kernel_flavour=shift;
my $kernel_major=shift;
my $sub_arch=shift;
my @kernel_versions=@ARGV;

my $deb_host_arch=`dpkg-architecture -qDEB_HOST_ARCH`;
chomp $deb_host_arch;

my @lists = ("pkg-lists/local");
my $t="";
foreach my $subtype (split "/", $type) {
	if (! length $t) {
		$t=$subtype;
	}
	else {
		$t="$t/$subtype";
	}
	push @lists, ("pkg-lists/$t/local", "pkg-lists/$t/common",
	              "pkg-lists/$t/$deb_host_arch.cfg");
	push @lists, "pkg-lists/$t/$deb_host_arch/$sub_arch.cfg" if $sub_arch;
}

while (@lists) {
	my $list=pop @lists;
	if (! -e $list) {
		print STDERR "warning: missing list, $list, for type $type\n"
			if $list !~ /local$/ && $list !~
			m#$deb_host_arch/$sub_arch.cfg$#;
	}
	else {
		open (LIST, $list) || die "open $list $!";
		while (<LIST>) {
			chomp;

			# includes
			if (/^#include \"(.*)\"/) {
				my $include=$1;
				if (-e "pkg-lists/kernel_specific/$kernel_major/$include") {
					push @lists, "pkg-lists/kernel_specific/$kernel_major/$include";
				}
				else {
					push @lists, "pkg-lists/$include";
				}
			}
			
			# comments
			s/^#.*//;
			next unless length;
			
			# normal kernel version substitution
			if (/\${kernel:Version}/) {
				foreach my $v (@kernel_versions) {
					my $l=$_;
					$l=~s/\${kernel:Version}/$v-$kernel_flavour/g;
					print "$l\n";
				}
				next; # move on to the next line
			}

			# if nothing else matches print the line untouched
			print "$_\n";
		    }
		close LIST;
	}
}
