#!/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: scan the commits being pushed and block the push if one contains malware, so it can't spread to
#    GitHub from this machine. (Not the working folder: what matters is what leaves, whichever branch is checked out.)
# 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
#
# checkrepo exit codes: 0 clean, 1 malware, 2 worth a look, 4 the scan could not finish.
# Before a push, "could not check" is NOT "clean": a missing Python or scanner, a scan that failed or took longer than
# ARDVANE_SCAN_SECONDS (default 120) blocks the push with the reason. To push anyway: ARDVANE_HOOK_FAILOPEN=1 git push ...
# (one push, and Ardvane says so), or git push --no-verify. The after-clone / pull / switch checks only warn.

name="$(basename "$0")"
CHECKREPO="${CHECKREPO:-$HOME/.checkrepo/checkrepo.py}"
SCAN_SECONDS="${ARDVANE_SCAN_SECONDS:-120}"
MAX_COMMITS=200

# find_python: sets $py to a Python 3.8+ (empty if none)
find_python() {
  py=""
  local c
  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
}

# run_scan ARGS...: checkrepo --quiet ARGS with a hard time limit; returns its exit code, or 0 if Python or the scanner is
# missing (only the warn-only hooks use this).
run_scan() {
  [ -f "$CHECKREPO" ] || return 0
  find_python
  [ -n "$py" ] || return 0
  "$py" "$CHECKREPO" --quiet --max-seconds="$SCAN_SECONDS" "$@" </dev/null >&2   # never let the scan read the hook's stdin (git's ref list)
}

# materialize SHA DIR [changed]: write the files of a commit into DIR without touching the working tree or index
# (all of them, or just the ones that commit changed)
materialize() {
  local idx="$2.index"
  GIT_INDEX_FILE="$idx" git read-tree "$1" 2>/dev/null || return 1
  if [ "$3" = "changed" ]; then
    git diff-tree -r -m --root --no-commit-id --name-only --diff-filter=ACMRT -z "$1" 2>/dev/null |
      GIT_LFS_SKIP_SMUDGE=1 GIT_INDEX_FILE="$idx" git -c core.fsmonitor=false checkout-index -f -z --stdin --prefix="$2/" 2>/dev/null
    local a=${PIPESTATUS[0]} b=${PIPESTATUS[1]}
    [ "$a" -eq 0 ] && [ "$b" -eq 0 ] || return 1
  else
    GIT_LFS_SKIP_SMUDGE=1 GIT_INDEX_FILE="$idx" git -c core.fsmonitor=false checkout-index -a -f --prefix="$2/" 2>/dev/null || return 1
  fi
  rm -f "$idx"
}

# push_blocked WHY: a push that could not be checked stops here unless the person said to go ahead
push_blocked() {
  if [ -n "${ARDVANE_HOOK_FAILOPEN:-}" ]; then
    echo "Ardvane: this push was NOT scanned ($1). ARDVANE_HOOK_FAILOPEN is set, so it goes ahead." >&2
    return 0
  fi
  printf '\033[1;31m%s\033[0m\n' "PUSH BLOCKED: Ardvane could not check what you are pushing ($1). Nothing was sent." >&2
  echo "   To push anyway, once:  ARDVANE_HOOK_FAILOPEN=1 git push ...    or:  git push --no-verify" >&2
  exit 1
}

is_zero() { [ -z "${1//0/}" ]; }

# scan_push REFS: scan the tip of each pushed ref in full, and the files every other new commit changed (so malware added
# in one commit and removed in the next is still seen). Returns the scanner's exit code, 4 if it could not run.
scan_push() {
  local tmp rc tips commits="" capped=0 line local_sha remote_sha list c
  tmp="$(mktemp -d "${TMPDIR:-/tmp}/ardvane-push.XXXXXX")" && tmp="$(cd "$tmp" && pwd)" || return 4   # normalised: no "//"
  tips="$(printf '%s\n' "$1" | awk 'NF >= 4 && $2 !~ /^0+$/ { print $2 }' | sort -u)"   # skip branch deletions
  while read -r line; do
    set -- $line
    [ $# -ge 4 ] || continue
    local_sha="$2"; remote_sha="$4"
    is_zero "$local_sha" && continue
    list=""
    if is_zero "$remote_sha"; then      # a new branch: only commits no remote branch has yet
      list="$(git rev-list --max-count=$((MAX_COMMITS + 1)) "$local_sha" --not --remotes 2>/dev/null)"
    else
      list="$(git rev-list --max-count=$((MAX_COMMITS + 1)) "$local_sha" --not "$remote_sha" 2>/dev/null)" ||
        list="$(git rev-list --max-count=$((MAX_COMMITS + 1)) "$local_sha" --not --remotes 2>/dev/null)"
    fi
    commits="$commits"$'\n'"$list"
  done < <(printf '%s\n' "$1")
  commits="$(printf '%s\n' "$commits" | awk 'NF && !seen[$1]++')"
  if [ "$(printf '%s\n' "$commits" | awk 'NF' | wc -l | tr -d ' ')" -gt "$MAX_COMMITS" ]; then
    commits="$(printf '%s\n' "$commits" | head -n "$MAX_COMMITS")"
    echo "Ardvane: this push has a lot of new commits; scanned the newest $MAX_COMMITS commits." >&2
  fi
  for c in $tips; do
    materialize "$c" "$tmp/$(git rev-parse --short=12 "$c")" || { rm -rf "$tmp" "$tmp.index"; return 4; }
  done
  for c in $commits; do
    case " $(echo $tips) " in *" $c "*) continue ;; esac     # a tip is scanned whole already
    materialize "$c" "$tmp/$(git rev-parse --short=12 "$c")" changed || { rm -rf "$tmp" "$tmp.index"; return 4; }
  done
  "$py" "$CHECKREPO" --quiet --each --all-files --max-seconds="$SCAN_SECONDS" "$tmp" </dev/null 2>&1 |
    sed "s#$tmp/\([0-9a-f][0-9a-f]*\)#commit \1 (being pushed)#" >&2
  rc=${PIPESTATUS[0]}
  rm -rf "$tmp" "$tmp.index"
  return $rc
}

case "$name" in
  post-checkout)
    # $3 = 1 for a branch checkout / clone, 0 for a single-file checkout
    [ "$3" = "1" ] && run_scan "$(git rev-parse --show-toplevel 2>/dev/null)"
    ;;
  post-merge|post-rewrite)
    run_scan "$(git rev-parse --show-toplevel 2>/dev/null)"
    ;;
  pre-push)
    # git sends "<local ref> <local sha> <remote ref> <remote sha>" per ref on stdin; keep it for the repo's own hook
    refs="$(cat)"
    if [ -n "$(printf '%s\n' "$refs" | awk 'NF >= 4 && $2 !~ /^0+$/')" ]; then     # nothing to check when only deleting branches
      find_python
      if [ ! -f "$CHECKREPO" ]; then
        push_blocked "the scanner is missing: $CHECKREPO"
      elif [ -z "$py" ]; then
        push_blocked "Python 3.8 or newer is not installed"
      else
        scan_push "$refs"
        case $? in
          0|2) ;;
          1) 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 ;;
          *) push_blocked "the scan could not finish" ;;
        esac
      fi
    fi
    ;;
esac

local_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/$name"
if [ -x "$local_hook" ]; then
  if [ "$name" = "pre-push" ]; then
    [ -n "$refs" ] && refs="$refs"$'\n'
    printf '%s' "$refs" | "$local_hook" "$@"
    exit $?
  fi
  exec "$local_hook" "$@"
fi
exit 0
