#!/bin/bash
# jamesbond 2011
# v2 - use awk instead of bash4

PKGFILE=Packages-puppy-fd64-offical
PKGFILE_OLD=${PKGFILE}-$(date +%F-T%T)
PKGFILE_NEW=${PKGFILE}-new

# 1. backup original file
if [ -f $PKGFILE ]; then
	cp $PKGFILE $PKGFILE_OLD
fi

# 2. append list of files to the PKGFILE
echo >> $PKGFILE
echo ==ENDS== >> $PKGFILE
for f in $(echo *.pet); do
	echo ${f%.pet}
done >> $PKGFILE

# 3. transfer processing to awk now (awk has associative array which simplifies matter)
awk -F"|" '
BEGIN { pkglist=1; 
}
{
	# 4. collect pkgs and files 
	if ($0 == "==ENDS==") pkglist=0;
	else if ($0 != "") {
		if (pkglist==1) {
			pkgs[$1]=$0
		} else files[$1]=$0
	}
}

END {
	#for (f in files) print f;	
	
	# 5. remove pkgs no longer existing
	for (p in pkgs) {
		if (p in files) pkgs2[p]=pkgs[p]
	}
	delete pkgs
	#for (p in pkgs2) print p;
	
	# 6. remove files already exist in pkgs2
	for (f in files) {
		if (! (f in pkgs2)) files2[f]=files[f]
	}
	delete files
	#for (f in files2) print f;
	
	# 6. get the pet.specs for each new files2
	for (f in files2) {
		petspec=""
		cmd1="xzcat " f ".pet 2> /dev/null | tar -O -xf - ./" f "/pet.specs 2> /dev/null"
		cmd2="xzcat " f ".pet 2> /dev/null | tar -O -xf - " f "/pet.specs 2> /dev/null"
		cmd3="tar -O -xf " f ".pet ./" f "/pet.specs 2> /dev/null"
		cmd4="tar -O -xf " f ".pet " f "/pet.specs 2> /dev/null"		
		cmd1 | getline petspec
		if (petspec == "") cmd2 | getline petspec  # try other form of petspec
		if (petspec == "") cmd3 | getline petspec  # try other form of compression
		if (petspec == "") cmd4 | getline petspec  # try other form of compression / petspec
		if (petspec != "") pkgs2[f]=petspec; 
		else print f " does not have pet.specs" > "/dev/stderr"
	}
	
	# 7. print the output - this will be our new file
	for (p in pkgs2) print pkgs2[p];
}
' < $PKGFILE  > $PKGFILE_NEW
sort $PKGFILE_NEW > $PKGFILE
rm $PKGFILE_NEW


