#!/usr/bin/perl

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

$RPMI = "export LANG=C; rpm -qpi";

$EXT = "metadata";

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

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

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

	##
	## File
	##

	$FILENAME = $line;
	$FILENAME =~ s/[\r\s\n\t]//i;
	$FILENAME = "$FILENAME.$EXT";
	if(@ARGV < 1){
		open(DATA, ">> $FILENAME");
	} else {
		open(DATA, ">> $OUTDIR/$FILENAME");
	}

	##
	## rpm -qi
	##

	@contents = `$RPMI $INDIR$line`;
	foreach $content(@contents){

		&replaceLabel($content);
		#print "$content";
		@parts = split(/\ :\ /, $content);

		for($i = 0; $i < $#parts; $i++){
			$parts[$i] =~ s/[\r\s\t]//i;
			$parts[$i] =~ s/ +$//;

			if($parts[$i] eq "Name"){
				print DATA "Name: $parts[$i+1]\n";
				$i++;
			} elsif ($parts[$i] eq "Version") {
				print DATA "Version: $parts[$i+1]\n";
				$i++;
			} elsif ($parts[$i] eq "Release") {
				print DATA "Release: $parts[$i+1]\n";
				$i++;
			} elsif ($parts[$i] eq "Install_Date") {
				$i++;
			} elsif ($parts[$i] eq "Group") {
				$i++;
			} elsif ($parts[$i] eq "Size") {
				$i++;
			} elsif ($parts[$i] eq "Signature") {
				$i++;
			} elsif ($parts[$i] eq "Packager") {
				$i++;
			} elsif ($parts[$i] eq "URL") {
				$i++;
			} elsif ($parts[$i] eq "Summary") {
				print DATA "Summary: $parts[$i+1]";
				$i++;
			} elsif ($parts[$i] eq "Description") {
				$i++;
			} elsif ($parts[$i] eq "Relocations") {
				$i++;
			} elsif ($parts[$i] eq "Vendor") {
				print DATA "Vendor: $parts[$i+1]";
				$i++;
			} elsif ($parts[$i] eq "Build_Date") {
				print DATA "Build: $parts[$i+1]";
				$i++;
			} elsif ($parts[$i] eq "Build_Host") {
				$i++;
			} elsif ($parts[$i] eq "Source_RPM") {
				$i++;
			} elsif ($parts[$i] eq "License") {
				$i++;
			} else {
			}
		}
	}

	close(DATA);
}

sub replaceLabel(){
	$content =~ s/Relocations:/ : Relocations :/i;
	$content =~ s/Vendor:/ : Vendor :/i;
	$content =~ s/Build Date:/ : Build_Date :/i;
	$content =~ s/Build Host:/ : Build_Host :/i;
	$content =~ s/Source RPM:/ : Source_RPM :/i;
	$content =~ s/License:/ : License :/i;
#	$content =~ s/Name        :/ : Name :/i;
#	$content =~ s/Version     :/ : Version :/i;
#	$content =~ s/Release     :/ : Release :/i;
	$content =~ s/Install Date:/Install_Date :/i;
#	$content =~ s/Group       :/ : Group :/i;
#	$content =~ s/Size        :/ : Size :/i;
#	$content =~ s/Signature   :/ : Signature :/i;
#	$content =~ s/Packager    :/ : Packager :/i;
#	$content =~ s/URL         :/ : URL :/i;
#	$content =~ s/Summary     :/ : Summary :/i;
#	$content =~ s/Description :/ : Description :/i;
}


