#!/usr/bin/env bash
# pre-commit hook: run ShellCheck on every shell script in the repo.
#
# This mirrors the CI check in .gitea/workflows/tests.yaml so the local
# lint and the CI lint cannot drift apart. Enable it in a clone with:
#
#   git config core.hooksPath githooks

set -u

if ! command -v shellcheck >/dev/null 2>&1; then
    echo "pre-commit: shellcheck not found on PATH, skipping lint." >&2
    echo "pre-commit: install it with 'pacman -S shellcheck'; CI still enforces it." >&2
    exit 0
fi

# Same file set as CI: *.sh plus the extensionless bash scripts in
# airootfs/usr/local/bin picked up by their shebang.
# find's stderr is dropped because localrepo/end4-pkgbuilds/*/pkg is left
# at mode d--x--x--x by makepkg and prints "Permission denied" locally.
sh_files=$(
    {
        find . -name '*.sh' -not -path './.git/*' 2>/dev/null
        find airootfs/usr/local/bin -type f ! -name '*.sh' \
            -exec grep -lE '^#!(/usr/bin/env bash|/bin/bash)' {} + 2>/dev/null
    } | sed '/^$/d' | sort -u
)

if [ -z "$sh_files" ]; then
    echo "pre-commit: no shell scripts found."
    exit 0
fi

failed=0
while IFS= read -r f; do
    if shellcheck -x -s bash "$f"; then
        echo "  ok   $f"
    else
        echo "  FAIL $f" >&2
        failed=1
    fi
done <<< "$sh_files"

if [ "$failed" -ne 0 ]; then
    echo "" >&2
    echo "pre-commit: ShellCheck failed. Fix the issues above, or bypass with:" >&2
    echo "  git commit --no-verify" >&2
    exit 1
fi

exit 0
