#!/bin/sh
# Created by Kapil Hari Paranjape <kapil@imsc.res.in>
# Based on inputs from Antonio Ospite <ospite@studenti.unina.it>
# This creates the new .orig.tar.gz if there is an update
set -e

# Uncomment this to debug
#set -x

CHANGELOGS="bugfixes2.txt bugfixes3.txt bugfixes4.txt"
NEWS="bugfixes.txt"
STYFILES="DraTex.sty AlDraTex.sty ProTex.sty AlProTex.sty"
#EITSCR="http://www.cse.ohio-state.edu/~gurari/temp/nogjava.perl"
#FIXJAVA="nogjava.perl"

# Use the watch file and uscan
# "uscan" exit is 1 even when there *is* a new file!
USCANOUT=$(uscan --report) || /bin/true

if [ -z "$USCANOUT" ] 
then
	echo "Existing source is up-to-date."
	exit 0
fi

# Extract information from the uscan report

URL=$(expr "$USCANOUT" : '.*\(http:\/\/.*\.tar\.gz\).*')
VERSION=$(expr "$USCANOUT" : '.*Newer version (\([0-9]*\)).*')

T4HTFIXURL=$(dirname "$URL")
T4HTURL=$(dirname "$T4HTFIXURL")
LIT="$T4HTFIXURL/tex4ht-lit.zip"
STYURL=$(expr "$T4HTURL" : '\(.*~[^/]*\)/.*')/tpf

ARCHIVE=$(basename $URL)
DIR=$(basename $ARCHIVE .tar.gz)

echo -n "Creating temporary directory for download ..."
TMPDIR=$(mktemp -d)
echo "Done."

OLDIR=$PWD

echo -n "Downloading the new sources ..."
cd $TMPDIR
if ! (wget -q $URL)
then
	echo "Error: Could not download $URL"
	exit 201
fi
if ! (wget -q $LIT)
then
	echo "Error: Could not download $LIT"
	exit 202
fi
for txtfile in $NEWS $CHANGELOGS 
do
	htmlfile=$(basename $txtfile .txt).html
	if ! (w3m -dump $T4HTURL/$htmlfile > $txtfile)
	then
		echo "Error: Could not download $T4HTURL/$htmlfile"
		exit 203
	fi
done
for sty in $STYFILES
do
	if ! (wget -q $STYURL/$sty)
	then
		echo "Error: Could not download $STYURL/$sty"
		exit 204
	fi
done
#if ! (wget -q $EITSCR -O $FIXJAVA)
#then
#	echo "Error: Could not download $FIXJAVE"
#	exit 205
#fi
echo "Done."

echo -n "Unpacking the source ..."
if [ -e $ARCHIVE ]
then
	tar xzf $ARCHIVE

	# Fix unnecessary execute permissions
	find $DIR/src ! -type d | xargs -i chmod -x \{\}

	# Fix unnecessary execute permissions
	find $DIR/texmf ! -type d | xargs -i chmod -x \{\}
else
	echo "Error: $ARCHIVE not found"
	exit 211
fi

if [ -e tex4ht-lit.zip ]
then
	if type -path unzip 
	then
		unzip -d $DIR/lit -aqq tex4ht-lit.zip
	else
		7z x -o$DIR/lit -tzip -y tex4ht-lit.zip
	fi
	mv $STYFILES $NEWS $CHANGELOGS $DIR/lit

	# Fix unnecessary execute permissions
	find $DIR/lit ! -type d | xargs -i chmod -x \{\}
else
	echo "Error: tex4ht-lit.zip not found"
	echo 212
fi
#mv $FIXJAVA $DIR/src
chmod +x $DIR/src/$FIXJAVA
echo "Done."

echo -n "Creating the new orig.tar.gz..."
mv $DIR tex4ht-${VERSION}.orig
GZIP="--best --rsyncable" tar czf $OLDIR/../tex4ht_${VERSION}.orig.tar.gz tex4ht-${VERSION}.orig
#tar czf $OLDIR/../tex4ht_${VERSION}.orig.tar.gz ${DIR}
echo "Done."

echo "Cleaning up ..."
cd $OLDIR
rm -rf $TMPDIR
echo "Done."

echo "New original sources are at ../tex4ht_${VERSION}.orig.tar.gz".

exit 0

