#!/bin/ksh -p

# The purpose of this script is to generate the internal menu listing
# for sites that we have already grabbed a catalog from
# This completely ignores what is in /etc/pkg-get.conf
#
# The reason this can be called directly from a Menu, and other
# scripts cannot, is that we generate the lines by hand, ourselves.
# The ones that dont work, use awk to generate output.
# We can USE awk. We just cant pipe it to fmli through stdout

cd /var/pkg-get


# output of last resort. If all else fails fall back to known good site
fallback(){
	# Assuming that pkgadm toplevel script will have
	# tried to set SITE and URL from existing pkg-get.conf file,
	# we should check for existing values, even if
	# the matching catalog file is in old format
	SITE=${SITE:-ftp.sunfreeware.com}
	URL=${URL:-ftp://ftp.sunfreeware.com/pub/freeware}

	print "name=$SITE"
	print 'description="Known site"'
	print action='`set -l SITE='${SITE} ';'
	print ' set -l URL='$URL ';'
	print ' run $MENUDIR/validatecatalog $URL; '
	print '             message "site '$SITE' selected"` close'
	print ""
}

#filelist=`awk 'NR == 1 && $1 == "#PKGADM" {print $2}' catalog-*`
filelist=`grep -l "#PKGADM" catalog-*`

print FILE LIST is $filelist
if [ "$filelist" = "" ] ; then
	fallback
	exit
fi


# Go through list of "catalog-xx" files, and assume they have
# the correct initial first line.
for f in $filelist ; do
	s=${f#catalog-}
	print name=${s}
	print 'description="Known site"'
	print action='`set -l SITE='${s} ';'
	print ' set -l URL='`head -1 $f |sed 's/^#PKGADM //'`
	print ' run $MENUDIR/validatecatalog $URL; '
	print '             message "site '$s' selected"` close'
	print ""
done

