#!/bin/sh
# SPDX-License-Identifier: MPL-2.0
#
# Ianitor pre-commit hook. Rejects staged files that must never be in git:
#   - binaries (anything git itself classifies as binary)
#   - private keys (PEM / OpenSSH / PKCS#8 / PGP headers, and key-store file names)
#   - files over 5 MB
#   - build output and dependencies (target/, node_modules/, dist/)
#
# Enable once per clone:   git config core.hooksPath .githooks
# Test it:                 sh .githooks/test-pre-commit.sh
# Plain POSIX sh: works in Git Bash on Windows and on Linux.

LIMIT=5242880   # 5 MiB

# Every check prints one "FAIL" line on stdout per problem (reasons go to stderr),
# so the loop can run in a pipeline subshell and still be counted here.
failures=$(
    # numstat prints "-<TAB>-<TAB>path" for files git treats as binary.
    git -c core.quotePath=false diff --cached --numstat --diff-filter=ACMR | while IFS= read -r line; do
        added=${line%%"	"*}
        rest=${line#*"	"}
        deleted=${rest%%"	"*}
        path=${rest#*"	"}
        if [ "$added" = "-" ] && [ "$deleted" = "-" ]; then
            printf 'pre-commit: rejected %s: binary file\n' "$path" >&2
            echo FAIL
        fi
    done

    git -c core.quotePath=false diff --cached --name-only --diff-filter=ACMR | while IFS= read -r path; do
        case "/$path" in
            */target/*|*/node_modules/*|*/dist/*)
                printf 'pre-commit: rejected %s: build output or dependency directory\n' "$path" >&2
                echo FAIL ;;
        esac

        base=${path##*/}
        case "$base" in
            *.pub) ;;
            *.key|*.p12|*.pfx|*.jks|*.keystore|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*)
                printf 'pre-commit: rejected %s: private key file name\n' "$path" >&2
                echo FAIL ;;
        esac

        # Size of the staged blob, not of the working-tree file.
        size=$(git cat-file -s ":$path" 2>/dev/null || echo 0)
        if [ "$size" -gt "$LIMIT" ]; then
            printf 'pre-commit: rejected %s: %s bytes is over the 5 MB limit\n' "$path" "$size" >&2
            echo FAIL
        fi

        if git cat-file -p ":$path" 2>/dev/null | grep -E -q -e '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'; then
            printf 'pre-commit: rejected %s: contains a private key\n' "$path" >&2
            echo FAIL
        fi
    done
)

case "$failures" in
    *FAIL*)
        printf 'pre-commit: commit blocked. Unstage the files above (git rm --cached <file>).\n' >&2
        exit 1 ;;
esac
exit 0
