#!/bin/bash

# A basic pre-commit hook intended to help perform XML file validation.
# The actual validation is supported by the TethysL API, and this script
# uses HTTPie to make the validation requests.
# See https://docs.mbari.org/tethysl/misc/xmlvalidation/.
#
# Install this hook by copying it as `.git/hooks/pre-commit` in your
# lrauv-mission clone.  Note that this is a client-side hook.
#
# By default, validation will be strict.
# You can use `git config hooks.xmlValidation <level>` to adjust
# the desired validation level, one of strict, basic, or none.

# Validation level:
xmlValidation=$(git config hooks.xmlValidation)

if [ "$xmlValidation" == "none" ]; then
    exit 0
fi

# Redirect output to stderr.
exec 1>&2

# Extended depending on level of validation:
api="https://okeanids.mbari.org/tethysl-engine"

if [ -z "$xmlValidation" ] || [ "$xmlValidation" == "strict" ]; then
    api="$api/validateXml"
elif [ "$xmlValidation" == "basic" ]; then
    api="$api/validateXmlBasic"
else
    echo "ERROR: unexpected value hooks.xmlValidation=$xmlValidation"
    echo "See: .git/hooks/pre-commit"
    exit 1
fi

# Collects all failed validations, if any:
outlistfile=$(mktemp)

# Validates a particular file
function validateXml {
    filter=$1
    filename=$2
    outfile=$(mktemp)
    echo "- $filter $filename:" >> "$outfile"
    http -pb --ignore-stdin --timeout=2.5 \
         POST "$api" @$(pwd)/$filename Accept:text/plain >> "$outfile" 2>&1
    if grep -qs Error "$outfile"; then
        any_error=yes
        cat "$outfile" >> "$outlistfile"
        echo >> "$outlistfile"
        echo >> "$outlistfile"
    fi
}

# Validate any added (A) or modified (M) xml files:
for filter in A M; do
    for filename in $(git diff --cached --name-only --diff-filter=$filter); do
        if [ "${filename##*.}" == "xml" ]; then
            echo "- Validating $filter $filename ..."
            validateXml "$filter" "$filename"
        fi
    done
done

if [ ! -z ${any_error} ]; then
    echo
    echo "Error: Attempting to commit invalid XML file(s) using xmlValidation=$xmlValidation"
    echo
    cat "$outlistfile"
    echo '-----------------------------------------------------------------'
    echo 'You can use `git config hooks.xmlValidation <level>` to adjust the'
    echo "desired validation level: one of strict, basic, or none."
    echo
    exit 1
fi
