#!/usr/bin/env bash
# Refuse to commit boboko-core "local mode" wiring (see bin/core-mode).
#
# Local mode points composer.json / package.json and both lockfiles at
# ../boboko-core, which doesn't exist on the server, so committing any of them
# breaks the build for everyone. Runs as the git pre-commit hook
# (.githooks/pre-commit) and only looks at what is staged: you can keep working
# in local mode and commit everything else — just leave these four unstaged.
set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

staged=$(git diff --cached --name-only --diff-filter=ACMR)
is_staged() { printf '%s\n' "$staged" | grep -qx "$1"; }
show() { git show ":$1"; }

problems=()

# Same detection as bin/core-mode. The leading quote keeps "_repositories"
# (the parked block) out of the match.
if is_staged composer.json &&
    show composer.json | sed -n '/"repositories": \[/,/"type"/p' | grep -q '"type": "path"'; then
    problems+=("composer.json: \"repositories\" is the local path repo")
fi
if is_staged package.json &&
    show package.json | sed -n '/"dependencies": {/,/}/p' | grep -q '"@boboko/core": "file:'; then
    problems+=("package.json: @boboko/core is file:../boboko-core")
fi
if is_staged composer.lock &&
    show composer.lock | grep -A14 '"name": "boboko/core"' | grep -q '"type": "path"'; then
    problems+=("composer.lock: boboko/core is locked to the local path")
fi
if is_staged package-lock.json &&
    show package-lock.json | grep -A6 '"node_modules/@boboko/core": {' | grep -q '"link": true'; then
    problems+=("package-lock.json: @boboko/core is a link to ../boboko-core")
fi

[ ${#problems[@]} -eq 0 ] && exit 0

{
    echo "!!! Commit blocked: boboko-core local-mode wiring is staged."
    printf '      - %s\n' "${problems[@]}"
    echo
    echo "    Unstage them and keep working in local mode:"
    echo "        git restore --staged composer.json composer.lock package.json package-lock.json"
    echo "    or switch back first:"
    echo "        bin/core-mode repo"
} >&2
exit 1
