#!/bin/sh
# aither-vcs-fragment — capture the new commit as a semantic edit-op.
# Best-effort: the commit already happened, so a capture failure is logged to
# <git-dir>/vcs-capture.log and NEVER breaks the commit. Skip paths are LOUD,
# never silent: if the fragment cannot resolve HEAD or the awgit CLI it logs
# why — a silent skip is how a dead capture reads as "nothing to capture".
#
# GOTCHA: git invokes post-commit with NO arguments. The fragment must resolve
# the new commit from `git rev-parse --verify HEAD` — assuming `$1` is the sha
# made the automatic capture exit silently on every real commit while manual
# invocations (which passed the sha) worked fine.
set -u
GITDIR="$(git rev-parse --git-dir 2>/dev/null)" || GITDIR=".git"
LOG="$GITDIR/vcs-capture.log"
SHA="${1:-}"
if [ -z "$SHA" ]; then
  SHA="$(git rev-parse --verify HEAD 2>/dev/null)"
fi
[ -n "$SHA" ] || {
  echo "vcs: capture skipped — no sha and cannot resolve HEAD" >> "$LOG" 2>&1
  exit 0
}
ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" || {
  echo "vcs: capture skipped — not a git worktree (hook cwd: $PWD)" >> "$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: capture skipped -- no runnable awgit (tried awgit, python3, python, py)" >> "$LOG" 2>&1
  exit 0
fi
$AWGIT_RUN capture --sha "$SHA" >> "$LOG" 2>&1 || true
exit 0
