#!/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 - libdivvun version 0.3.12-alpha"
        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/local/bin/divvun-validate-pipespec" ] && [ -e "$d"/pipespec.dtd ]; then
    dtd="$d"/pipespec.dtd
elif [ -e "/usr/local/share/libdivvun/pipespec.dtd" ] ; then
    dtd=/usr/local/share/libdivvun/pipespec.dtd
fi

/usr/bin/xmllint --dtdvalid "${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
