#!/usr/bin/perl

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


$DPKGA = "dpkg --get-selections";
$DPKGS = "dpkg -s";
$DPKGD = "apt-cache showpkg";

$FILENAME = "tm3-data.txt";
$count = 0;

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

@lines = `$DPKGA`;

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

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

	$count++;

	##
	## File
	##

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

	##
	## dpkg -s
	##

	print DATA "Name.$count=$package\n";

	@contents = `$DPKGS $package`;
	foreach $content(@contents){
		$content =~ s/[\r\s\n\t]//i;
		if(index("$content", "Version:") >= 0){
			$version = substr($content, 8);
			print DATA "Version.$count=$version";
		} elsif (index("$content", "Installed-Size:") >= 0){
			$size = substr($content, 15);
			if(index("$size", ".") > 0){
				$size = substr($size, 0, index("$size","."));	
				$size = $size."\n";
			}
			print DATA "Size.$count=$size";
		} elsif (index("$content", "Section:") >= 0){
			$section = substr($content, 8);
			print DATA "MajorGroup.$count=$section";
		}
	}

	##
	## apt-cache showpkg
	##
	@contents = `$DPKGD $package`;	
	$num = 0;
	foreach $content(@contents){

		$content =~ s/[\r\n\t]//i;

		if(index("$content", "Reverse Depends:") >= 0){
			$num = 0;
		}
		if (index("$content", "Dependencies:") >= 0){
			$num = $num - 1;
			print DATA "Required_Num.$count=$num\n";
		}
		$num++;
	}

	print DATA "\n";
		
	close(DATA);
}



