#!/bin/sh
# FIXME: use autoconf & automake

export LIVEDTD=livedtd.pl
export BATIK_RASTERIZER_JAR="$HOME/bin/batik-1.5.1/batik-rasterizer.jar"
export XML_CATALOG_FILES=/etc/xml/catalog
# FIXME: make this the other way around - configure.ac sends the version to chmspec.docbook.in
export VERSION=`sed -ne 's/<!ENTITY version "\(.*\)">.*/\1/1p' < src/chmspec.docbook`
# alias xsltprocoutfiles = sed -ne 's/^Writing \(.*\) for [a-z]\+(.*)/\1/1p'

export LIVEDTDS="col.dtd hhcolreg.dat.dtd"
export IMAGES=""
export SVG2PNG="FIftiMain.svg cover.svg"
export DOCS="README TODO AUTHORS THANKS NEWS ChangeLog package"
export STYLESHEETS=
export PNGCRUSHES="chm.png chs.png cover.png extern-link.png FIftiMain.png hhc.png hhk.png hhp.png hhs.png home.png itsf.png mailto-link.png new.png next.png note.png prev.png save.png up.png"
export COPY="../img/*.ico ../src/*.dtd ../css/* ../README ../TODO ../AUTHORS ../THANKS ../NEWS ../ChangeLog"

# Check the source is valid
echo Validating the source against the docbook DTD...
test "x$DEVEL" = "x" || xmllint --nonet --valid --noout src/chmspec.docbook || exit 1
echo ...done

# Remove existing packages in the current directory
rm --force --recursive chmspec-*

# Make the HTML package
mkdir chmspec-$VERSION-html
cd chmspec-$VERSION-html

# Convert the SVG files using batik
# rsvg/ksvg don't cut it just yet :(
echo Converting SVG images to PNG...
for f in $SVG2PNG; do
	ff="`basename $f .svg`"
	test -s "../img/$ff.png" || java -jar $BATIK_RASTERIZER_JAR -bg 255.255.255.255 "../img/$f"
done
echo ...done

# Process the docbook
echo Converting docbook files to html...
xsltproc --nonet --output chmspec.html ../xsl/chunk.xsl ../src/chmspec.docbook
echo ...done

# Copy the other stuff
echo Copying other files...
for f in $COPY; do
	cp "$f" . ;
done
echo ...done

# Crush PNGs
echo Crushing PNGs...
for f in $PNGCRUSHES; do pngcrush "../img/$f" "$f" || cp "../img/$f" "$f"; done
echo ...done

# Process the DTDs using LiveDTD
echo Making LiveDTD files...
for f in $LIVEDTDS; do
	ff="`basename $f .dtd`.livedtd"
	mkdir -p $ff
	$LIVEDTD --outdir "$ff" "../src/$f"
	test -s "$ff/index.html" && sed -i -e 's!href="'$f'"!href="'$ff'/index.html"!g' *.html
done
echo ...done

cd ..

echo Creating archives for distribution...
# Move all the files into a zip file (after verification of the zip)
zip -rmT chmspec-$VERSION-html.zip chmspec-$VERSION-html
echo ...HTML distribution done...
# Make the source package
mkdir chmspec-$VERSION
cp $DOCS chmspec-$VERSION
cp --parents `find img/ src/ css/ xsl -not -ipath \*CVS\* -not -iname SciTE.properties -not -iname .\*` chmspec-$VERSION
# Move all the source code into a tarball
tar --gzip --create --file chmspec-$VERSION.tar.gz chmspec-$VERSION && rm --force --recursive chmspec-$VERSION
echo ...Source distribution done.

# Unzip the html archive: useful for development
test "x$DEVEL" = "x" || unzip chmspec-$VERSION-html.zip
