#!/bin/sh

set -e

name=`basename "$0"`
dir=`dirname "$0"`
src=`cd "$dir/.." && pwd`
bin="$src/bin"

die () {
        echo >&2 "$1"
        exit 1
}

usage () {
        die "usage: $name"
}

case "$#" in
0)
;;
*)
	usage
;;
esac

book='mlton.book'
pages='.pages'
pdf='mlton-guide.pdf'
script='.script'
titlepage='title.html'
tmp="/tmp/mlton-guide.$$"
version=`cat $src/doc/guide/MLTONWIKIVERSION`

rm -rf "$tmp"
mkdir "$tmp"
cd "$tmp"

( cd "$src/doc/guide" && tar -cf - . ) | tar -xf -

# The grep -v takes out files that aren't wiki pages.
# Hope that no files contain spaces or other specials -> `cat "$pages"` dies
ls -1 | grep -v '\.' | grep -v "MLTONWIKIVERSION" >"$pages"

echo 'Massaging HTML.'

for f in `cat "$pages"`; do
cat >"$script" <<EOF
/^<table bgcolor = lightblue/,+29d
s;\(<body .*\);\1\n<h1>$f</h1>;
s;<FONT[^>]*>;;g
s;</FONT>;;g
s;\(<div id="content"\);\1;
s;<td colspan = 3;<td align = right;
s;<img src=\"\(http://mlton.org[^>]*\)>;<img src="moin-www.png"><a href=\"\1>image</a>;g
s;MLTONWIKIVERSION;$version;g
EOF
	"$bin/msed" -f "$script" <"$f" >.tmp
	mv .tmp "$f"
done

echo 'Generating PDF titlepage.'
cat >"$titlepage" <<EOF
<html>
<head><title>MLton Guide ($version)</title></head>
<body>
<h1>MLton Guide</h1>
<p>
This is the guide for MLton, an open-source, whole-program,
optimizing Standard ML compiler.
</p>

<p>
This guide was generated automatically from the MLton wiki,
available online at <a href="http://mlton.org/">http://mlton.org</a>.
It is up to date for MLton $version.
</p>

</body>
</html>
EOF

echo 'Generating htmldoc script.'
(
cat <<EOF
#HTMLDOC 1.8.24 Open Source
-f $pdf
-t pdf13 
--bodyfont times 
--bottom 0.50in 
--browserwidth 680 
--charset iso-8859-1 
--color
--compression=9 
--effectduration 1.0 
--embedfonts 
--firstpage p1 
--fontsize 11.0 
--fontspacing 1.2 
--footer ..1
--header t.c
--headfootfont Helvetica 
--headfootsize 11.0 
--headingfont Helvetica 
--jpeg=0 
--left 1.00in 
--links 
--linkstyle underline 
--no-encryption 
--no-pscommands 
--no-strict
--no-xrxcomments 
--nup 1 
--pageduration 10 
--pageeffect none 
--pagelayout single 
--pagemode document 
--portrait 
--right 0.50in 
--size Universal 
--title 
--top 0.50in 
--webpage 
$titlepage
Home
Index
EOF

grep -v '^\(Home\|Index\)$' "$pages" 
) >"$book"

echo 'Running htmldoc.'
htmldoc --batch "$book" || true

mv "$pdf" "$src/doc/guide"

rm -rf "$tmp"
