#!/bin/sh
# script/generate: regenerate mfer/mf.pb.go from mfer/mf.proto, and record
# the hash of that mf.proto in mfer/mf.proto.sha256. Nothing else
# regenerates mf.pb.go: it is committed, so building and checking need no
# protoc. A test fails while mf.proto no longer matches the recorded hash.
#
# Needs exactly the protoc and protoc-gen-go versions named in the header of
# the committed mf.pb.go (README.md says how to install them). Another
# version writes a different mf.pb.go, so the script refuses to run.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

# protoc 33.4 names itself v6.33.4 in the mf.pb.go header.
PROTOC_VERSION="33.4"
PROTOC_GEN_GO_VERSION="v1.36.11"

# require_version <command> <its exact --version output>
require_version() {
    actual="$("$1" --version 2>/dev/null || true)"
    if [ "$actual" != "$2" ]; then
        echo "generate: needs $2 on PATH, found: ${actual:-none}" >&2
        echo "  README.md says how to install it." >&2
        exit 1
    fi
}

# sha256 <file>: print "<hash>  <file>", with sha256sum, or with shasum
# where there is no sha256sum.
sha256() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1"
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1"
    else
        echo "generate: needs sha256sum or shasum on PATH" >&2
        exit 1
    fi
}

main() {
    cd "$ROOT/mfer"
    require_version protoc "libprotoc $PROTOC_VERSION"
    require_version protoc-gen-go "protoc-gen-go $PROTOC_GEN_GO_VERSION"
    # Hashed before regenerating, so a missing hash tool stops the script
    # before it changes anything. Regenerating leaves mf.proto as it is.
    proto_hash="$(sha256 mf.proto)"
    go generate .
    echo "$proto_hash" >mf.proto.sha256
}

main "$@"
