#!/bin/sh
# Pre-commit hook: enforce `precious lint` on staged files and
# block direct commits to the default branch.
#
# Install (run once per clone):
#   scripts/pre-commit --init

set -eu

if [ "${1:-}" = "--init" ]; then
    repo_root=$(git rev-parse --show-toplevel)
    hook_path="$repo_root/.git/hooks/pre-commit"
    target="../../scripts/pre-commit"
    if [ -e "$hook_path" ] && [ ! -L "$hook_path" ]; then
        echo "ERROR: $hook_path exists and is not a symlink." >&2
        echo "Move or remove it, then re-run scripts/pre-commit --init." >&2
        exit 1
    fi
    chmod +x "$repo_root/scripts/pre-commit"
    ln -sf "$target" "$hook_path"
    echo "Installed pre-commit hook: $hook_path -> $target"
    exit 0
fi

# Block direct commits to the default branch.
default_branch="master"
branch=$(git symbolic-ref --short HEAD 2>/dev/null || true)
if [ "$branch" = "$default_branch" ]; then
    echo "ERROR: Direct commits to '$default_branch' branch are not allowed." >&2
    echo "Please create a feature branch instead:" >&2
    echo "  git checkout -b feature/your-feature-name" >&2
    exit 1
fi

# Run precious lint on staged files
if ! precious lint -q --staged; then
    echo "pre-commit hook failed: precious lint found issues with staged files" >&2
    echo "Please run 'precious tidy -q --staged' and try again" >&2
    exit 1
fi
