#!/usr/bin/perl

##
## Licensed Materials - Property of IBM
## Open Platform Trust Services - An open source TCG PTS
## (C) Copyright International Business Machines Corp. 2007
##

$DPKG = "/usr/bin/dpkg";

$EXT = "metadata";

if(@ARGV < 1){
	print "USAGE: perl $0 [output dir (optional)]\n\n";
} else {
	$DIR = $ARGV[0];
	if(!-d $DIR){
		mkdir $DIR;
	}
}

@lines = `$DPKG --get-selections`;

foreach $line(@lines){
	#print "> $line";

	##
	## Get package name
	##

	@words = split(/\s/, $line);
	$package = $words[0];

	##
	## Filename
	##

	$FILENAME = "$package"."-".&getversion($package);
	$FILENAME =~ s/[\r\s\n\t]//i;
	$FILENAME = "$FILENAME.$EXT";

	#print "$FILENAME\n";

	if(@ARGV < 1){
		open(DATA, ">> $FILENAME");
	} else {
		open(DATA, ">> $DIR/$FILENAME");
	}


	@infos = `$DPKG -s $package`;

	$START = 0;
	foreach $info(@infos){
		#$info =~ s/[\r\s\n\t]//i;

		if(index("$info", "Description:") >= 0){
			$START = 1;
			$tmp = "$info";
			$tmp =~ s/\n//;
		} elsif($START == 1) {
			$tmp = "$tmp $info";
			$tmp =~ s/\n//;
		} else {
			print DATA "$info";
		}

	}
	print DATA "$tmp";

	close(DATA);
}


sub getversion(){
	@infos = `$DPKG -s $package`;
	foreach $info(@infos){
		$info =~ s/[\r\s\n\t]//i;
		if(index("$info", "Version:") >= 0){
			$info =~ s/:/_/g;
			return substr($info, 8);
		}
	}
}
