#!/bin/sh
target=${1:-platform}
hostname=${2:-${HOST}}

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

file=config-${hostname}.xml
if [ ! -f out/${file} ]; then
  echo "ERROR: out/${file} does not exist."
  exit 5
fi
[ -L out/config.xml ] && rm -f out/config.xml
ln -s ${file} out/config.xml

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

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 7
     ;;
esac

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

( 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'
