#!/bin/sh
# Installed by `vibey-gh install` — do not edit; edit the template in vibey-gh.
#
# Appends the provenance trailer to any commit message that lacks it, so the rule holds
# locally without anyone having to remember it. CI enforces the same trailer, so a commit
# made without this hook fails the pull request rather than slipping through.


# Resolve the CLI. `vibey-gh` on PATH is the normal case, but a project virtualenv that
# has not been activated is just as normal — and a gate that reports "not installed"
# when the tool IS installed is a gate people learn to bypass. Look where it actually
# lives before giving up. Hooks run from the top of the working tree.
vibey_gh() {
  if command -v vibey-gh >/dev/null 2>&1; then
    vibey-gh "$@"
  elif [ -n "${VIRTUAL_ENV:-}" ] && [ -x "${VIRTUAL_ENV}/bin/vibey-gh" ]; then
    "${VIRTUAL_ENV}/bin/vibey-gh" "$@"
  elif [ -x ".venv/bin/vibey-gh" ]; then
    ./.venv/bin/vibey-gh "$@"
  elif [ -x "venv/bin/vibey-gh" ]; then
    ./venv/bin/vibey-gh "$@"
  elif python3 -c "import vibey_gh.cli" >/dev/null 2>&1; then
    python3 -m vibey_gh.cli "$@"
  elif python3 -c "import vibey_bootstrap.gh.cli" >/dev/null 2>&1; then
    python3 -m vibey_bootstrap.gh.cli "$@"   # pre-split layout
  else
    return 127
  fi
}


msg_file="$1"
key=$(vibey_gh trailer-key 2>/dev/null || echo "Made-With")
trailer=$(vibey_gh trailer 2>/dev/null || echo "Made-With: Made with ❤️ by [Vibey](https://adammatthewsteinberger.github.io/vibey/), Developed by [Adam Matthew Steinberger](https://hire.adam.matthewsteinberger.com/) ([@adammatthewsteinberger](https://github.com/adammatthewsteinberger/)).")

# A pre-existing project hook runs first and may do its own thing.
[ -x "$(dirname "$0")/commit-msg.local" ] && "$(dirname "$0")/commit-msg.local" "$@"

# Already present in any case — nothing to do.
if grep -qiE "^${key}:[[:space:]]*[^[:space:]]" "$msg_file"; then
  exit 0
fi

# A comment-only or empty message means an aborted commit; leave it alone.
if ! grep -qvE '^\s*(#.*)?$' "$msg_file"; then
  exit 0
fi

printf '\n%s\n' "$trailer" >> "$msg_file"
