#!/usr/bin/perl
# Add an item to the manifests, or update an existing item.
# Also cleans manifests of any items that do not exist any longer.
# May be run with no parameters to only clear old stuff.
my $file=shift;
my $desc=shift;
my @udeblists=@ARGV;

if (length $file && ! length $desc) {
	print STDERR "warning: no manifest info for $file\n";
}

my $sep=" -- ";

my %manifest;
if (-e "dest/MANIFEST") {
	open (IN, "dest/MANIFEST") || die $!;
	while (<IN>) {
		chomp;
		my ($key, $value)=split(/\s*$sep/, $_, 2);
		$manifest{$key}=$value;
	}
	close IN;
}

if (-e "dest/MANIFEST.udebs") {
	my $file;
	open (IN, "dest/MANIFEST.udebs") || die $!;
	while (<IN>) {
		chomp;
		if (/^([\S]+)/) {
			$file=$1;
		}
		elsif (defined $file) {
			s/^\s+//;
			push @{$manifest_udebs{$file}}, $_;
			$seen{$_}=1;
		}
	}
}

if (length $file) {
	$file=~s!(\./)?dest/!!;

	$manifest{$file}=$desc;
	
	delete $manifest_udebs{$file};
	foreach my $udeblist (@udeblists) {
		if (-e $udeblist) {
			my %seen;
			open (IN, "$udeblist") || die $!;
			while (<IN>) {
				chomp;
				push @{$manifest_udebs{$file}}, $_ unless $seen{$_};
			}
		}
	}
}

my $longest=0;
foreach my $item (keys %manifest, keys %manifest_udebs) {
	if (! -e "dest/$item") {
		delete $manifest{$item};
		delete $manifest_udebs{$item};
		next;
	}
	if (length $item > $longest) {
		$longest=length $item;
	}
}

if (! %manifest) {
	unlink "dest/MANIFEST";
	unlink "dest/MANIFEST.udebs";
	exit;
}

open (OUT, ">dest/MANIFEST") || die "write dest/MANIFEST: $!";
foreach my $item (sort keys %manifest) {
	print OUT $item.(" " x ($longest - length $item))."$sep$manifest{$item}\n";
}
close OUT;

open (OUT, ">dest/MANIFEST.udebs") || die "write dest/MANIFEST.udebs: $!";
foreach my $file (sort keys %manifest_udebs) {
	print OUT "$file\n";
	foreach my $i (@{$manifest_udebs{$file}}) {
		print OUT "\t$i\n";
	}
}
