#!/bin/bash

PROGDIR=$(dirname $(readlink -f $0))

while getopts "r:d:" c
do
	case $c in
	d) SNAPDIR=$OPTARG;;
	esac
done
shift $[OPTIND-1]

PRODUCT=$1
if [ "$PRODUCT" = "" ]; then
	echo Usage: "mksnap [-d dir] <product>"
	exit
fi

SNAPDIR=${SNAPDIR:-$HOME/www/mkgmap.org.uk/docroot/download}

print_product_line() {
	file=$1
	set $file $(ls -Lhtl $file| sed 's/  */ /' | sed 's/ \+/ /g' | cut -d ' ' -f5-9)

	case $file in
	*-src.tar.gz)
		return;;
	*latest*)
		fileref=$(ls -l $file | cut -d' ' -f11)
		;;
	*)
		fileref=$file
		;;
	esac

	name=${file%.tar.gz}
	refbase=${fileref%.tar.gz}

	if [ -f $file ]; then
		echo '<tr>'
		echo "<td>$name</td>"
		case $name in
		*.jar)
			echo "<td>&nbsp;<a href='$fileref'>[.jar]</a>&nbsp;"
			;;
		*)
			echo "<td>&nbsp;<a href='$fileref'>[.tar.gz]</a>&nbsp;"
			echo "<a href='$refbase.zip'>[.zip]</a>&nbsp;"
			echo "<a href='${refbase}-src.tar.gz'>[src]</a> </td>"
			;;
		esac
		echo "<td>&nbsp;</td>"
		echo "<td>$3 $4</td>"
		echo "<td>$5</td>"
		echo "<td>&nbsp;</td>"
		echo "<td>$2</td>"
		echo '</tr>'
	fi
}

cd $SNAPDIR

sed -e "s/%(PRODUCT)s/$PRODUCT/" $PROGDIR/skel-top > $PRODUCT.html

(
#print_product_line $PRODUCT-latest.tar.gz
for file in $(ls -t)
do
	case $file in
	$PRODUCT-r*tar.gz)
		print_product_line $file
		;;
	*)
		;;
	esac
done
) >> $PRODUCT.html

if [ $(echo *.jar | wc -c) -gt 6 ] ; then
	echo '</table><h1>Branch builds</h1>
	<p>These jar files are latest builds of recent development branches.
	They are useful if you want to quickly test a branch without having
	obtain and build it.  The source code is available via subversion.
	<p>As this is an automatic process, some of the branches might be
	already merged with the main line, or abandoned and of course they
	may not work.
	<table>
	' >> $PRODUCT.html

	for file in $(ls -t)
	do
		case $file in
		$PRODUCT-*jar)
			print_product_line $file $(ls -Ltl $file| sed 's/  */ /' | sed 's/ \+/ /g' | cut -d ' ' -f6-9,11-)
			;;
		*)
			;;
		esac
	done >> $PRODUCT.html
else
	echo '<tr><td></td></tr>' >> $PRODUCT.html
fi

if [ $PRODUCT = mkgmap ]; then
	PRODUCT_AD=9104507573
else
	PRODUCT_AD=0835769470
fi

sed -e "s/%(PRODUCT_AD)s/$PRODUCT_AD/" $PROGDIR/skel-bot >> $PRODUCT.html
