#! /bin/sh
#
# Find all submission root directories, and pack the submission
# into an appropriate directory in the BBS section.  Also copy
# the associated product info file to the BBS section, alongside
# the archive.

tmpd=`date +%j%H%M%S`
tmp="/tmp/sh1-$tmpd"
home=`pwd`
grep "^[^/]*/[^/]*/[^/]*$" <$1 >$tmp
bbsroot=$2

for i in `cat $tmp`
do
	dname=`dirname $i`
	fname=`basename $i`
	cd $dname
	prodname=""
	lhafiles=""
	pifilein=""
	if test -d $fname
	then
		if test -f $fname/Product-Info
		then
			prodname=$fname
			lhafiles="$fname"
			pifilein=$fname/Product-Info
			if test -f $fname.info
			then
				lhafiles="$fname.info $lhafiles"
			fi
		else
			echo WARNING 'pwd'/$fname is missing a Product-Info file
		fi
	elif test -f $fname.pi
	then
		prodname=$fname
		lhafiles="$fname $fname.pi"
		pifilein=$fname.pi
		if test -f $fname.info
		then
			lhafiles="$lhafiles $fname.info"
		fi
	fi
	if test -n "$prodname"
	then
		case "$prodname" in
			*.anim) prodname=`basename $prodname .anim`;;
			*.jpeg) prodname=`basename $prodname .jpeg`;;
			*.jpg) prodname=`basename $prodname .jpg`;;
			*) ;;
		esac
		if test -n "$pifilein"
		then
			version=`echo $pifilein | pitool -f - -b -F "%V" - | tr -d " \t"`
			case "$version" in
				"");;
				"?.?");;
				*) prodname="$prodname-$version";;
			esac
		fi

		bbsdir=`dirname $dname`
		lhaname=$prodname.lha
		pifileout=$lhaname.pi

		#echo "==========="
		#echo "dname = $dname"
		#echo "bbsdir = $bbsdir"
		#echo "prodname = $prodname"
		#echo "lhaname = $lhaname"
		#echo "lhafiles = $lhafiles"
		#echo "pifilein = $pifilein"
		#echo "pifileout = $pifileout"

		if test ! -d $bbsroot/$bbsdir
		then
			echo "mkdir -p $bbsroot/$bbsdir"
			mkdir -p $bbsroot/$bbsdir
		fi
		# Begin FIXME - this should be an option, comment it out for now
		#  if test -f $bbsroot/$bbsdir/$lhaname
		#  then
		#  	echo "rm -f $bbsroot/$bbsdir/$lhaname"
		#  	rm -f $bbsroot/$bbsdir/$lhaname
		#  fi
		# End FIXME
		if test -f $bbsroot/$bbsdir/$lhaname
		then
			echo "Not superceding $bbsroot/$bbsdir/$lhaname"
		else
	
			# Add each of the files/directories to the lha archive.
			# We do it this way because the shareware version of
			# lha misbehaves if handled all args at once.

			while [ -n "${lhafiles}" ] ; do
				set ${lhafiles}; file=$1; shift; lhafiles=$*
				echo "lha -mraxeq a $bbsroot/$bbsdir/$lhaname $file"
				lha -mraxeq a $bbsroot/$bbsdir/$lhaname $file
			done

			# Copy the associated product info file over.

			echo "cp $pifilein $bbsroot/$bbsdir/$pifileout"
			cp $pifilein $bbsroot/$bbsdir/$pifileout
		fi
	fi
	cd $home
done
rm -f $tmp
