#!/bin/bash
# Install the navigation guard beside an existing Forgejo pre-receive hook.
# The existing hook remains first in the execution chain and is preserved as a
# rollback file.  This script must run only in an authorized server session.

set -euo pipefail

HOOK_DIR="${1:-}"
MODE="${2:-reject}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SUPPORT_DIR="${HOOK_DIR}/guanghu-navigation-guard"
ORIGINAL="${HOOK_DIR}/pre-receive.before-navigation"
HOOK="${HOOK_DIR}/pre-receive"

if [ -z "${HOOK_DIR}" ] || [ ! -d "${HOOK_DIR}" ]; then
    echo "usage: $0 <existing-bare-repo-hooks-dir> [reject|notify]" >&2
    exit 2
fi
if [ ! -f "${HOOK}" ]; then
    echo "refusing: existing pre-receive hook is required for chained install" >&2
    exit 2
fi
if [ -e "${ORIGINAL}" ]; then
    echo "refusing: rollback hook already exists: ${ORIGINAL}" >&2
    exit 3
fi

mkdir -p "${SUPPORT_DIR}"
install -m 0755 "${SCRIPT_DIR}/pre-receive-guard.py" "${SUPPORT_DIR}/pre-receive-guard.py"
install -m 0755 "${SCRIPT_DIR}/navigation-memory-guard.py" "${SUPPORT_DIR}/navigation-memory-guard.py"
python3 -m py_compile "${SUPPORT_DIR}/pre-receive-guard.py" "${SUPPORT_DIR}/navigation-memory-guard.py"

cp -p "${HOOK}" "${ORIGINAL}"

cat > "${HOOK}" <<WRAPPER
#!/bin/bash
# Guanghu chained pre-receive: preserved legacy hook first, navigation guard second.
set -o pipefail
HOOK_DIR="${HOOK_DIR}"
ORIGINAL="${ORIGINAL}"
SUPPORT_DIR="${SUPPORT_DIR}"
REFS="\$(mktemp "\${HOOK_DIR}/.pre-receive.refs.XXXXXX")"
trap 'rm -f "\${REFS}"' EXIT
cat > "\${REFS}"
"\${ORIGINAL}" < "\${REFS}" || exit \$?
PRE_RECEIVE_MODE="${MODE}" python3 "\${SUPPORT_DIR}/pre-receive-guard.py" < "\${REFS}"
WRAPPER
chmod 0755 "${HOOK}"

echo "installed chained pre-receive guard"
echo "rollback: cp -p ${ORIGINAL} ${HOOK}"
