#!/bin/sh
# Staged blobs need checking because `git add -f` bypasses .gitignore.

set -e

fail() {
	echo "pre-commit: refusing to commit cartridge data." >&2
	echo "$1" >&2
	echo "" >&2
	echo "pokerecomp is bring-your-own-ROM. Keep game files outside the repo." >&2
	exit 1
}

staged=$(git diff --cached --name-only --diff-filter=AM)
[ -z "$staged" ] && exit 0

blocked=$(printf '%s\n' "$staged" | grep -Ei '\.(gb|gbc|gba|sav|srm|rom|ips|bps|ups)$' || true)
[ -n "$blocked" ] && fail "  blocked by extension:
$(printf '%s\n' "$blocked" | sed 's/^/    /')"

# 512 KiB is below the smallest Game Boy ROM.
LIMIT=524288
large=""
IFS='
'
for path in $staged; do
	case "$path" in
		addons/*|assets/*) continue ;;
	esac
	size=$(git cat-file -s "$(git rev-parse ":$path")" 2>/dev/null || echo 0)
	[ "$size" -ge "$LIMIT" ] && large="$large    $path ($size bytes)
"
done

[ -n "$large" ] && fail "  suspiciously large for source:
$large
  If it is legitimate, commit with --no-verify."

exit 0
