#!/bin/sh
# Checks engine/embed/model/ against its SHA256SUMS: the sums of the files there, made
# again and compared byte for byte with the file, so a file missing, added, changed, or
# a line edited in SHA256SUMS all fail. No links anywhere in it. Exit 1 with the reason.
#   engine/embed/check-model          check
#   engine/embed/check-model --write  write SHA256SUMS from the files there (after a new
#                                     conversion; see convert.py)
# MODEL.md, .gitattributes and SHA256SUMS at the top are not part of the model.
set -eu
MODEL="$(cd "$(dirname "$0")" && pwd)/model"
[ -d "$MODEL" ] && [ ! -L "$MODEL" ] || { echo "check-model: engine/embed/model/ is missing"; exit 1; }
cd "$MODEL"
if [ -n "$(find . -type l)" ]; then
    echo "check-model: engine/embed/model/ holds a link: $(find . -type l | head -1)"; exit 1
fi
sums() {
    find . -type f ! -path ./SHA256SUMS ! -path ./MODEL.md ! -path ./.gitattributes ! -name .DS_Store \
        | sed 's|^\./||' | LC_ALL=C sort | while IFS= read -r f; do shasum -a 256 "$f"; done
}
if [ "${1:-}" = "--write" ]; then
    sums > SHA256SUMS
    echo "check-model: wrote SHA256SUMS ($(wc -l < SHA256SUMS | tr -d ' ') files)"
    exit 0
fi
[ -f SHA256SUMS ] || { echo "check-model: engine/embed/model/SHA256SUMS is missing"; exit 1; }
sums | cmp -s - SHA256SUMS \
    || { echo "check-model: engine/embed/model/ differs from its SHA256SUMS (a file missing, added or changed)"; exit 1; }
