#!/bin/sh -e
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*-

PROG="${0##*/}"
PREFIX="/usr/share/docs-build/docsbuild"
SUBST=/usr/bin/subst
SED=/bin/sed
IDX=index.html

Fatal() {
  printf "$PROG: Fatal: %s\n" "$*" >&2
  exit 1
}

outdir="$1" && shift || Fatal "more arguments required"
echo "OUT: $outdir"
target_document="$1" && shift 
params="$*"

find doc -name "*.htm*" | while read i; do 
    cat $i | fgrep charset | $SED 's/.*charset=\([^"]\+\)".*/\1/' | xargs -i iconv -c -f {} -t UTF-8 $i -o $i.utf || Fatal "iconv to UTF-8 failed"
    $SUBST 's/charset=[^"]\+"/charset=UTF-8"/' $i.utf || echo "no file $i.utf"
    mv -f $i.utf $i
done

cp -r doc/* "$outdir"
cd "$outdir"

bname="$(basename $target_document .html)"
[ -n "$bname" ] || Fatal "Cannot get basename: $target_document"

if [ ! -f "$IDX" ]; then 
    cp "$PREFIX/$IDX" .
    $SUBST "s/\!ROOTDOC\!/$bname.html/" $IDX
fi
