#!/bin/sh

usage () {
    cat <<EOF
Usage:
  divvun-validate-pipespec FILE - error if FILE is not valid pipespec xml
EOF
}

case "$1" in
    -V|--version)
        echo "$0 - Divvun gramcheck version 0.3.10"
        exit
        ;;
    -h|--help)
        usage
        exit
        ;;
    "") usage
        exit 1
        ;;
esac

file="$1"

if [ ! -e "${file}" ]; then
    echo "ERROR: '${file}' file not found"
    exit 1
fi


# If it looks like we're not installed, use the pipespec.dtd of the same
# dir as this script; otherwise assume we're installed:
d=$(dirname "$0")
if [ "$0" != "/usr/bin/divvun-validate-pipespec" ] && [ -e "$d"/pipespec.dtd ]; then
    dir="$d"
else
    dir=/usr/share/divvun-gramcheck
fi

/usr/bin/xmllint --dtdvalid "${dir}"/pipespec.dtd --noout "${file}"

if default=$(/usr/bin/xmllint --xpath "/pipespec/@default-pipe" "${file}" 2>/dev/null); then
    defaultval="${default##*=}"
    res=$(/usr/bin/xmllint --xpath "/pipespec/pipeline/@name=${defaultval}" "${file}")
    if ! test x"${res}" = xtrue; then
        echo "ERROR:$default specified in ${file}, but no pipelines have the name ${defaultval}"
        exit 1
    fi
fi
