#!/bin/sh
set -eu
# Git's quarantine environment must be preserved to read incoming objects.
while read -r old new ref; do
    case "$new" in
        0000000000000000000000000000000000000000) continue ;;
        *[!0-9a-f]*|'') echo 'Invalid object ID' >&2; exit 1 ;;
    esac
    if ! commit=$(git rev-parse --verify "$new^{commit}"); then
        echo 'Gitleaks: only refs pointing to commits are accepted.' >&2
        exit 1
    fi
    echo "Gitleaks: scanning history for $ref" >&2
    if ! /opt/gitleaks/bin/gitleaks git . \
        --config /opt/gitleaks/config/gitleaks.toml \
        --gitleaks-ignore-path /opt/gitleaks/config/empty.gitleaksignore \
        --ignore-gitleaks-allow --redact=100 --no-banner --no-color \
        --timeout 120 --log-opts="$commit"; then
        echo 'Push rejected: Gitleaks found secrets or could not complete the scan.' >&2
        echo 'Remove secrets from the affected commits before retrying.' >&2
        exit 1
    fi
done
