#!/bin/ksh -p

# This script gets passed in a list of packages from an FMLI form.
# It will download them, if they are not local.
# If there are any unmet dependancies, it will also attempt to
# download those packages from the same site.
# It will then add all the packages.
#

# This should be set to the method to download to stdout.
# like pkg-get, we have to use wildcards and dumps to stdout.
# (Until I update the catalog file to be smarter. sigh)
#
GRABFILE=${GRABFILE:-"wget -nv --dot-style=mega --passive-ftp --glob=on -O /dev/fd/1"}
# ADMINFILE is to tell pkgrm to shut up and do the job
ADMINFILE=$MENUDIR/pkg.admin

# This is the "base" url for a site.
URL="$1" ; shift
SITE=${URL##*//}
SITE=${SITE%%/*}
if [ "$SITE" = "" ] ; then
	# guess that URL is a dir path /xxx/yyy
	SITE="$URL"
fi
print "pkginstall: URL is $URL"
print "            SITE is $SITE"

if [ "$1" == "ALL" ] ; then
	printf DEBUG: doing "ALL" expansion
	ITEMS=`$MENUDIR/pkglist $SITE ALL`
else
	ITEMS=$@
fi

print Items to add are $ITEMS
print ""

#################################################################
# Now it gets semi-ugly. Need to handle all the different methods
# of getting the media. Handle directory-installs differently
# from download installs.


# we expect that "URL" is set to a plain directory name at this point.
dir_install(){
	for pkgname in $ITEMS ; do
		print Adding $pkgname
		pkgadd -d $URL -a $ADMINFILE $pkgname
	done
}

# site_install takes the name of file(s) to download
# This assumes URL is set to the toplevel of a sunfreeware.com mirror
# It will grab the file to DYNAMICDIR, aka /ar/run/something
# So hopefully you have enough swap to take up the download.
site_install(){
	# read in possible wget configuration tweaks
	# Note that it sets 'url', but NOT 'URL'
	if [[ -f /etc/pkg-get.conf ]] ; then
		. /etc/pkg-get.conf
	fi
	CPU=`uname -p`
	OSREV=`uname -r`
	fullurl=$URL/$CPU/$OSREV

	cd $DYNAMICDIR
	for file in $ITEMS ; do
		$GRABFILE $fullurl/$file'-*' >$file
		if [[ $? -ne 0 ]] ; then
			print ERROR: download of $file failed
			rm $file
			continue;
		fi

		if [[ ! -s $file ]] ; then
			print ERROR: download is zero length file
			rm $file
			continue
		fi

		file $file | grep 'compressed ' >/dev/null
		if [[ $? -eq 0 ]] ; then
			print unzipping... $file
			gzip -d -c $file >$file.ungz
			if [[ $? -ne 0 ]] ; then
				print ERROR: unzip of $file failed
				rm $file.ungz
				continue;
			fi
			mv $file.ungz $file
		fi
		pkgname=`nawk 'NR==2 {print $1;exit}' $file`
		
		pkgadd  -a $ADMINFILE -d $file $pkgname
		rm $file
	done
	
}


case $URL in
	/*)
		dir_install #$ITEMS
	;;
	*)
		site_install #$ITEMS
	;;
esac

