#!/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";

$MD5  = "md5sum";
$SHA1 = "sha1sum";

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

if($ARGV[0] eq "md5"){
	$EXT = "md5.filelist";
	$HASH = $MD5;
}
if($ARGV[0] eq "sha1"){
	$EXT = "sha1.filelist";
	$HASH = $SHA1;
}


@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");
	}

	##
	## Get installed file path of one package ($package)
	##

	@contents = `$DPKG -L $package`;
	foreach $content(@contents){

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

		if(-f $content && -B $content){
			##
			## Get the hash value of one file ($content)
			##
			#print "$content\n";

			$returned = `$HASH $content`;
			print DATA $returned;
		}
	}

	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);
		}
	}
}


