#!/bin/ksh

# This is a quickie script to auto-generate a table of contents for all
# the binary-package subdirs of a pkg-get compatible site, such
# as  sunfreeware.com

# It assumes that directory names are named on the basis of

# `uname -p`/`uname -r`

# It also expects that filenames will look like

#  softwarename-12345-[trailingstuff]

#
# Just call this script with the top level directory as an argument. eg:
#  makecontents ~ftp/pub/freeware
# Then for each of the subdirectories matching the above spec, it
# will generate a contents file, of the format
#   softwarename softwarerev pkgname
# For example,
#   bzip2 0.9.0c SMCbzip2
#
# Phil Brown, phil@bolthole.com June 22nd, 2007
#

#FTPTOP=/tmp/pkgdir


FTPTOP="$1"

if [[ "$FTPTOP" == "" ]] ; then
	print ERROR: you need to specify the top of the tree
	exit 1
fi

cd $FTPTOP
FTPTOP=`/bin/pwd`

# Extracts a pkg name from a pkgstream file
# prints NOTHING if does have the PaCkAgE magic on line 1
# otherwise, prints out the package name from line 2
# Works both with a filename, and as a filter
getpkgname(){
	awk 'NR==1{if ($2 != "PaCkAgE"){exit;}}
	     NR==2 {print $1; exit;}' $1
}

gencatalog(){
	ARCH=$1
	OSREV=$2
	if [[ "$OSREV" == "" ]] ; then
		echo "Internal error: function gencatalog called without args"
		return 1
	fi
	for f in * ; do
		case $f in
			catalog*|setup*)
				continue
			;;
		esac
				
		IFS='-'
		set $f
		pkgname="$1"
		pkgrev="$2"
		IFS=" "
		case $pkgrev in
			*0*|*1*|*2*|*3*|*4*|*5*|*6*|*7*|*8*|*9*)
			;;
			*)
			print No package version found for filename $f >/dev/fd/2
			print Need pkgname-0123456789-blah >/dev/fd/2
			continue;
		esac
		case $f in
		    *gz)
			pkg=`gzip -d -c $f | getpkgname`
			;;
		    *)
			pkg=`getpkgname $f`
			;;
		esac
		if [[ "$pkg" == "" ]] ; then
			print No package instance found in file $f >/dev/fd/2
		else
			print $pkgname $pkgrev $pkg $f
		fi

		# ideally we would extract the "DESC=" field from the
		# package.. but there isnt one currently anyways
	done
	
}


######################################################################
# main routine here

cd $FTPTOP

for ARCH in sparc i386 ; do
	cd $FTPTOP/$ARCH
	for OSREV in 5.* ; do
		if [[ "$OSREV" == '5.*' ]] ; then
			print ERROR: no appropriate subdirectories in $PWD
			exit 1
		fi

		cd $OSREV

		print "DOING $ARCH $OSREV NOW"
	  	gencatalog $ARCH $OSREV >catalog.tmp
		if [[ $? -ne 0 ]] ; then
			rm catalog.tmp
			print aborting new catalog generation for ${ARCH}-${OSREV}
		else
			mv catalog.tmp catalog
		fi
		cd ..
	done
done
