#!/bin/sh

findFile()
{
  local file=$1; shift
  for dir in "$@"; do
    local result=${dir}/${file}
    [ -f "${result}" ] && echo ${result} && return
  done
  echo "ERROR: Can't find ${file} in suggested places." 1>&2
  exit 2 # on FreeBSD this exit gets ignored, don't know why
}

#
# main
#

SGML_DIR=/usr/share/sgml
XML_DCL=` findFile xml.dcl \
	${SGML_DIR} \
	${SGML_DIR}/jade_dsl \
	${SGML_DIR}/declaration \
	/usr/local/share/sgml/docbook/dsssl/modular/dtds/decls ` \
|| exit 3

if ! jade=` which jade ` && jade=` which openjade `; then
  echo "ERROR: Can't find either jade or openjade."
  exit 4
fi

[ -L config.xml ] || ln -s config-${HOSTNAME}.xml config.xml
os_code=` sed -ne 's/<!ENTITY config.OS.CODE "\(.*\)">/\1/p' < config.xml `
if [ -z "${os_code}" ]; then
  echo "ERROR: No entity config.OS.CODE in config.xml"
  exit 5
fi

target=${1:-platform}
case ${target} in
  intro) dst_dir=_html; step_out=..;;
  platform) dst_dir="_html/${os_code}"; step_out=../..;;
  *) echo "ERROR: First argument must be either 'intro' or 'platform'"
     exit 6
     ;;
esac

[ -d ${dst_dir} ] && rm -f ${dst_dir}/*.html
mkdir -p ${dst_dir} || exit 7

( cd ${dst_dir} \
&& ${jade} -wall -t xml -i html -d "${step_out}/etc/ldp.dsl#html" \
	${XML_DCL} "${step_out}/${target}/main.xml" 2>&1
) | sed	-e '/: invalid value for "attributes" characteristic/d' \
	-e '/: unused parameter entity/d'
