#!/bin/sh
#
# Convert HTML documents to PDF
#
# Copyright (C) 2004 Klaus Weidner <kweidner@pobox.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: 
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Configure this to point to the location of the saved memory image.
# Generate it as follows:
#
#   clisp -x "(asdf::oos 'asdf:load-op :xml-render) (tt::save-image)"
#   gzip -9 clisp-xml-render.mem 
#   mv clisp-xml-render.mem.gz ~/lisp/images/clisp
#
IMAGE="$HOME/lisp/images/clisp/clisp-xml-render.mem.gz"

# Location of GNU CLISP binary
#CLISP=/usr/lib/clisp/full/lisp.run
CLISP=clisp

# avoid non-standard charsets...
LC_CTYPE=en_US
export LC_CTYPE

# WARNING: creates fixed-name temp files in current working directory.
# Don't use it if current dir is writable for untrusted users.

# Run through W3C "tidy" utility to clean up noncompliant HTML and
# convert to XHTML. See http://tidy.sourceforge.net/
#
# Not needed if input is already valid XHTML. Comment out the next
# line if you don't want to use it.
[ -z "$TIDY" ] && TIDY=$(which tidy)

### End of user configurable section

Usage () {
	echo "Usage: $(basename $0) FILE.html
Creates FILE.pdf in current working directory." >&2
	exit 1
}

[ $# -eq 1 ] || Usage

IN="$1"
OUT=$(basename "$IN" .html).pdf

if [ -x "$TIDY" ]
then
	XML=$(basename "$IN").tmp.xhtml
	"$TIDY" --quiet yes --show-warnings 0 -wrap 0 -asxhtml "$IN" > "$XML"
else
	XML="$IN"
fi

# Do the conversion
$CLISP -q -q -M $IMAGE -- "$XML" "$OUT"

[ -x "$TIDY" ] && rm -f "$XML"
