#!/usr/bin/perl

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


$PWD = `pwd`;
$PWD =~ s/[\r\s\n\t]//i;
$WORKDIR = "/tmp/debcheck";

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

if(@ARGV < 3){
	print "USAGE: perl $0 [deb_directory] [result_dir] [sha1/md5]\n\n";
	exit;
} else {
	$INDIR = $ARGV[0];
	$OUTDIR = $ARGV[1];
	if(!-d $OUTDIR){
		mkdir $OUTDIR;
	}
}

if($ARGV[2] eq "md5"){
        $EXT = "md5.filelist";
        $HASH = $MD5;
} elsif($ARGV[2] eq "sha1"){
        $EXT = "sha1.filelist";
        $HASH = $SHA1;
} else {
	print "USAGE: perl $0 [deb_directory] [result_dir] [sha1/md5]\n\n";
	exit;
}

opendir DIR, $INDIR;
@lines = grep { !m/^(\.|\.\.)$/g } readdir DIR;
close DIR;

foreach $line(@lines){
print "\n\n\n$line\n";

	##
	## File
	##

	$FILENAME = $line;
	$FILENAME =~ s/[\r\s\n\t]//i;
	$FILENAME = "$FILENAME.$EXT";
	open(DATA, "> $OUTDIR/$FILENAME");

	##
	## Get the hash value from each file
	##
	mkdir $WORKDIR;
	`dpkg-deb -x $INDIR/$line $WORKDIR`;

	chdir $WORKDIR;
	@files = `find .`;
	foreach $file(@files){
		if( -d $file ){
			rmdir($file);
		} else {
			$returned = `$HASH $file`;	
			print DATA $returned;
			unlink("$WORKDIR/$file");
		}
	}
	`rm -rf $WORKDIR`;
	chdir $PWD;

	close(DATA);
}
`rm -rf $WORKDIR`;


