#!/bin/bash
# =============================================================================
# Pre-Push Guardrail Hook
# Generated by Traqr CLI for {{PROJECT_DISPLAY_NAME}}
# =============================================================================
#
# Blocks direct git push to enforce the /ship workflow.
# This ensures all code goes through PR creation.
#
# To bypass (only /ship should do this):
#   {{SHIP_ENV_VAR}}=true git push ...
#
# =============================================================================

RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m'

# ── Non-blocking workspace-drift advisory (DevOps2 2026-05-22) ───────────────
# Surface workspace-symlink drift (e.g. node_modules/@traqr/<pkg> symlinks
# missing in worktrees created before that package landed) at push time — the
# recurring "worktree resolves main's stale dist → false-RED typecheck:scripts"
# trap. WARN-ONLY, and placed BEFORE the authorized-push early-exit below so it
# is visible on the /ship path (the only sanctioned push) yet never blocks: a
# hard-fail here would block /ship itself in every drifted worktree. Drift is
# non-fatal to the push and self-repairs with `npm install`. Guarded on the
# detector's presence so it no-ops where the script is absent.
DRIFT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ -n "$DRIFT_ROOT" ] && [ -f "$DRIFT_ROOT/scripts/check-workspace-symlinks.sh" ]; then
    if ! _drift=$(bash "$DRIFT_ROOT/scripts/check-workspace-symlinks.sh" 2>&1); then
        echo ""
        echo -e "${YELLOW}⚠ workspace-symlink drift (non-blocking — push continues):${NC}"
        echo "$_drift" | grep -E "MISSING|SHADOWED|^  - " | sed 's/^/    /'
        echo -e "${YELLOW}    Reconcile with: npm install   (at the repo root)${NC}"
        echo ""
    fi
fi
# ─────────────────────────────────────────────────────────────────────────────

BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Allow pushes on main (for /sync operations)
if [ "$BRANCH" = "main" ]; then
    exit 0
fi

# Check if this is an authorized push (set by /ship or /sync)
if [ "${{SHIP_ENV_VAR}}" = "true" ]; then
    exit 0
fi

# Block the push
echo ""
echo -e "${RED}======================================${NC}"
echo -e "${RED}   DIRECT PUSH BLOCKED${NC}"
echo -e "${RED}======================================${NC}"
echo ""
echo -e "${YELLOW}Use /ship to push changes. This ensures:${NC}"
echo "  - PR is created automatically"
{{#IF_TIER_3+}}echo "  - Slack notification sent to #{{SLACK_DEPLOY_CHANNEL}}"{{/IF_TIER_3+}}
echo "  - Proper merge workflow"
echo ""
echo -e "${YELLOW}In Claude Code:${NC}"
echo "  /ship \"Your PR title here\""
echo ""
echo -e "${YELLOW}If you REALLY need to force push (rare):${NC}"
echo "  {{SHIP_ENV_VAR}}=true git push ..."
echo ""
exit 1
