#!/usr/bin/env bash
# Pre-commit hook BiaOnline - controlli di sicurezza minimi.
# Attivare una sola volta con: git config core.hooksPath .githooks
# Funziona su Linux/Mac/Git Bash su Windows.

set -e

red() { printf "\033[0;31m%s\033[0m\n" "$1"; }
yellow() { printf "\033[0;33m%s\033[0m\n" "$1"; }
green() { printf "\033[0;32m%s\033[0m\n" "$1"; }

STAGED=$(git diff --cached --name-only --diff-filter=ACMR)
if [ -z "$STAGED" ]; then
    exit 0
fi

# 1. Blocca commit del file .env
if echo "$STAGED" | grep -E "^\.env$|^\.env\." > /dev/null; then
    red "[pre-commit] commit di .env bloccato. Usa .env.example per template."
    exit 1
fi

# 2. Blocca pattern ad alto rischio nei file PHP staged
RISKY=$(printf "%s\n" "$STAGED" | grep -E "\.php$" || true)
if [ -n "$RISKY" ]; then
    if echo "$RISKY" | xargs git show :./ 2>/dev/null | grep -nE "(^|[^a-zA-Z_])eval\s*\(" > /dev/null; then
        red "[pre-commit] uso di eval() rilevato nei file staged."
        exit 1
    fi
    if echo "$RISKY" | xargs git show :./ 2>/dev/null | grep -nE "unserialize\s*\(\s*\\\$_(GET|POST|REQUEST|COOKIE)" > /dev/null; then
        red "[pre-commit] unserialize() su input utente rilevato."
        exit 1
    fi
    if echo "$RISKY" | xargs git show :./ 2>/dev/null | grep -nE "withoutMiddleware\s*\(\s*['\"]auth['\"]" > /dev/null; then
        yellow "[pre-commit] withoutMiddleware('auth') trovato in file staged. Verificare che sia intenzionale."
    fi
fi

# 3. Heuristic secret scanner (regex base, leggera)
if echo "$STAGED" | xargs git show :./ 2>/dev/null | grep -nE "AIza[0-9A-Za-z_\-]{35}|sk-[A-Za-z0-9_\-]{30,}|GOCSPX-[A-Za-z0-9_\-]{20,}" > /dev/null; then
    red "[pre-commit] possibile API key rilevata nei file staged."
    exit 1
fi

# 4. Composer audit veloce se composer.lock e` nello staged
if echo "$STAGED" | grep -E "composer\.(json|lock)$" > /dev/null; then
    if command -v composer > /dev/null 2>&1; then
        yellow "[pre-commit] composer audit (puo` impiegare alcuni secondi)..."
        if ! composer audit --no-dev --no-interaction; then
            red "[pre-commit] composer audit ha trovato vulnerabilita`. Risolvere prima del commit."
            exit 1
        fi
    fi
fi

green "[pre-commit] tutti i controlli di sicurezza minimi sono passati."
exit 0
