#!/usr/bin/env bash
# sh-cherrypick post-commit: after a `git cherry-pick -x` lands, record the upstream SHA
# (recovered from the `(cherry picked from commit <sha>)` trailer) + the new local SHA into
# an UNTRACKED .git-local journal. Never edits tracked files. No-op for normal commits.
# Fail-safe: any internal error exits 0 so a commit is never aborted here.
set -uo pipefail

{
  msg="$(git log -1 --format=%B 2>/dev/null)" || exit 0
  up_sha="$(printf '%s\n' "$msg" \
    | sed -n 's/.*cherry picked from commit \([0-9a-f]\{7,40\}\).*/\1/p' | tail -1)"
  [ -z "$up_sha" ] && exit 0   # not a cherry-pick (or no -x) -> leave normal commits untouched

  local_sha="$(git rev-parse HEAD 2>/dev/null)" || exit 0
  gd="$(git rev-parse --absolute-git-dir 2>/dev/null)" || exit 0
  journal="$gd/sh-cherrypick-journal"
  ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  tab="$(printf '\t')"

  if ! { [ -f "$journal" ] && grep -q "^${up_sha}${tab}" "$journal" 2>/dev/null; }; then
    printf '%s\t%s\t%s\n' "$up_sha" "$local_sha" "$ts" >> "$journal"
  fi

  n="$(grep -c . "$journal" 2>/dev/null || echo '?')"
  echo "sh-cherrypick: journaled ${up_sha:0:12} (${n} pending) — run: make triage-reconcile" >&2
} || true

exit 0
