#!/bin/sh
# aither-vcs-fragment — stamp a stable Awgit-Change-Id into the commit message.
#
# git passes: $1 = message file, $2 = source (message|template|merge|squash|commit),
# $3 = sha (for commit/amend). chain.sh forwards "$@", so they arrive intact.
#
# NEVER fails the commit. A commit that cannot be written because an id could
# not be minted is a far worse outcome than a commit without an id: `push` can
# fall back to matching on sha, but a blocked commit loses work. Skips are
# logged rather than silent — a fragment that quietly does nothing is
# indistinguishable from one that is not installed, which is how the capture
# fragment once appeared to work while running on no commits at all.
set -u
GITDIR="$(git rev-parse --git-dir 2>/dev/null)" || GITDIR=".git"
LOG="$GITDIR/vcs-capture.log"
MSGFILE="${1:-}"
SOURCE="${2:-}"

[ -n "$MSGFILE" ] || {
  echo "vcs: change-id skipped — no message file argument" >> "$LOG" 2>&1
  exit 0
}
[ -f "$MSGFILE" ] || {
  echo "vcs: change-id skipped — message file $MSGFILE does not exist" >> "$LOG" 2>&1
  exit 0
}
# Find an interpreter that actually RUNS, in this order: awgit's own console
# script, then python3, then python, then the Windows launcher.
#
# Measured 2026-09-09 on the self-hosted Debian runner: `command -v python`
# is FALSE there -- Debian ships python3 and no `python` -- and awgit was
# installed with `pip install --target`, which puts no console script on PATH.
# Both arms of the old guard were therefore false, this fragment logged a skip
# and exited 0, and every commit was written with no Change-Id. 23 awgit tests
# failed on the publish lane naming assertions in awgit itself, and awgit
# 1.11.0 could not reach PyPI on any of the 6-hourly runs.
#
# `command -v` alone is not enough either (2026-08-21): a reinstall left
# `Scripts/awgit` as a Windows PE with no .exe extension, so `command -v` said
# yes and the exec died `Permission denied`. Presence is not usability -- ask
# the thing to RUN.
AWGIT_RUN=""
if awgit --version >/dev/null 2>&1; then
  AWGIT_RUN="awgit"
else
  for cand in python3 python py; do
    c="$(command -v "$cand" 2>/dev/null)" || continue
    if [ "$cand" = "py" ]; then
      "$c" -3 -c "import awgit.cli" >/dev/null 2>&1 && { AWGIT_RUN="$c -3 -m awgit.cli"; break; }
    else
      "$c" -c "import awgit.cli" >/dev/null 2>&1 && { AWGIT_RUN="$c -m awgit.cli"; break; }
    fi
  done
fi

if [ -z "$AWGIT_RUN" ]; then
  echo "vcs: change-id skipped -- no runnable awgit (tried awgit, python3, python, py)" >> "$LOG" 2>&1
  exit 0
fi
$AWGIT_RUN change-id ensure "$MSGFILE" --source "$SOURCE" >> "$LOG" 2>&1 || true
exit 0
