#!/usr/bin/env bash
# Ardvane — global git hook dispatcher.
# Installed as ~/.checkrepo/hooks/<hook-name> (all names point here) and enabled with:
#   git config --global core.hooksPath ~/.checkrepo/hooks
#
# 1) After clone / pull / branch switch: run the read-only malware scan (checkrepo) and warn.
# 2) Before push: block the push if malware is found, so it can't spread to GitHub from this machine.
# 3) Then hand over to the repository's own hook in .git/hooks/<name>, so per-repo hooks keep working.
# Repos that set their own core.hooksPath (Husky, lefthook) bypass this file — the daily routine covers them.
# Works on macOS, Linux and Git for Windows (which runs hooks with its bundled bash).
# To use it from your own hook instead, call it by hook name, e.g.  ~/.checkrepo/hooks/pre-push "$@" || exit 1

name="$(basename "$0")"
CHECKREPO="${CHECKREPO:-$HOME/.checkrepo/checkrepo.py}"

scan() {
  [ -f "$CHECKREPO" ] || return 0
  local py=""
  for c in python3 python py; do   # test each: on Windows "python3" may be a Microsoft Store stub that doesn't run
    if command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' >/dev/null 2>&1; then py="$c"; break; fi
  done
  [ -n "$py" ] || return 0
  "$py" "$CHECKREPO" --quiet "$(git rev-parse --show-toplevel 2>/dev/null)" >&2
}

case "$name" in
  post-checkout)
    # $3 = 1 for a branch checkout / clone, 0 for a single-file checkout
    [ "$3" = "1" ] && scan
    ;;
  post-merge|post-rewrite)
    scan
    ;;
  pre-push)
    scan
    if [ $? -eq 1 ]; then
      printf '\033[1;31m%s\033[0m\n' "PUSH BLOCKED by malware check. Nothing was sent." >&2
      echo "   If you are 100% sure this is a false alarm: git push --no-verify" >&2
      exit 1
    fi
    ;;
esac

local_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/$name"
if [ -x "$local_hook" ]; then
  exec "$local_hook" "$@"
fi
exit 0
