#!/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.
#
# Runs the protoc that script/bootstrap unpacks into bin/protoc, and the
# protoc-gen-go that bin/tools/go.mod pins. Another version of either
# writes a different mf.pb.go.
set -eu

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

# The protoc version script/bootstrap installs. protoc 33.4 names itself
# v6.33.4 in the mf.pb.go header.
PROTOC_VERSION="33.4"
PROTOC="$ROOT/bin/protoc/bin/protoc"

# 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() {
    # A bin/protoc left from before the pin moved fails here, until
    # script/bootstrap replaces it.
    actual="$("$PROTOC" --version 2>/dev/null || true)"
    if [ "$actual" != "libprotoc $PROTOC_VERSION" ]; then
        echo "generate: needs protoc $PROTOC_VERSION in bin/protoc," \
            "found: ${actual:-none}; run script/bootstrap" >&2
        exit 1
    fi
    # `go tool -n` builds protoc-gen-go from bin/tools and prints where the
    # binary is, without running it.
    plugin="$(cd "$ROOT/bin/tools" && go tool -n protoc-gen-go)"

    cd "$ROOT/mfer"
    # 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)"
    "$PROTOC" --plugin=protoc-gen-go="$plugin" \
        --go_out=paths=source_relative:. ./mf.proto
    echo "$proto_hash" >mf.proto.sha256
}

main "$@"
