#!/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 it installs into bin/. Another version of either writes a
# different mf.pb.go.
set -eu

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

# The versions 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"
PROTOC_GEN_GO_VERSION="v1.36.12"
PROTOC_GEN_GO="$ROOT/bin/protoc-gen-go"

# 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 or bin/protoc-gen-go left from before its 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
    actual="$("$PROTOC_GEN_GO" --version 2>/dev/null || true)"
    if [ "$actual" != "protoc-gen-go $PROTOC_GEN_GO_VERSION" ]; then
        echo "generate: needs protoc-gen-go $PROTOC_GEN_GO_VERSION in" \
            "bin/protoc-gen-go, found: ${actual:-none}; run script/bootstrap" >&2
        exit 1
    fi

    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="$PROTOC_GEN_GO" \
        --go_out=paths=source_relative:. ./mf.proto
    echo "$proto_hash" >mf.proto.sha256
}

main "$@"
