#!/bin/sh
APERTIUMDIR=/opt/osx/share/apertium
XMLLINT=/usr/bin/xmllint
XSLTPROC=/usr/bin/xsltproc
#!/bin/bash
# Makefile.am prepends APERTIUMDIR, XMLLINT, XSLTPROC and the right shebang

show_help () {
    cat <<EOF
USAGE: $(basename "$0") modes.xml
       $(basename "$0") modes.xml BASENAME
       $(basename "$0") -f modes.xml INSTALLDIR

Creates all modes under the 'modes/' subdirectory of the directory of
modes.xml, and further creates copies of installable modes in the same
directory as modes.xml.

If only modes.xml is given, all files refer only to datafiles under
the same directory as modes.xml.

If only modes.xml and BASENAME are given, installable modes will refer
to datafiles in ${APERTIUMDIR}/\${BASENAME}.

If -f is given, the second non-option argument INSTALLDIR is the full
path to where installed data files for installable modes are.


If a mode has attribute gendebug="yes", the script will also
auto-generate debug modes (e.g. -morph, -tagger, -chunker).

Use option -v to show the actual commands this script runs.
EOF
    exit 1
}

verbose=false
fullpath=false
OPTIND=1
while getopts "hHfv" opt; do
    case "$opt" in
        h|H)
            echo show_help
            exit 0
            ;;
        v)  verbose=true
            ;;
        f)  fullpath=true
            ;;
        '?')
            show_help >&2
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

if [[ $# -eq 0 ]]; then
     show_help >&2
     exit 1
fi

xmlfile="$1"
if [[ ! -e "${xmlfile}" ]]; then
    echo "ERROR: '${xmlfile}' file not found"
    exit 1
fi
xmldir=$(cd "$(dirname "${xmlfile}")"; pwd)

case $# in
    1) installdir="${xmldir}";;
    2) if ${fullpath}; then
           installdir="$2"
       else
           installdir="${APERTIUMDIR}/$2"
       fi
       ;;
    *) show_help >&2
       exit 1
       ;;
esac

$verbose && set -x
set -o pipefail # introduced in bash 3; available in OSX>=10.5; should be safe

[[ -d "${xmldir}"/modes ]] || mkdir "${xmldir}"/modes

"${XMLLINT}" --dtdvalid "${APERTIUMDIR}"/modes.dtd --noout "${xmlfile}" || exit $?

"${XSLTPROC}" "${APERTIUMDIR}"/modes2debugmodes.xsl "${xmlfile}" \
    | "${XSLTPROC}" --stringparam devdir "${xmldir}" \
                    --stringparam installdir "${installdir}" \
                    "${APERTIUMDIR}"/modes2bash.xsl \
                    - \
    | awk -f "${APERTIUMDIR}"/apertium-createmodes.awk
