#!/usr/bin/env bash
# pre-push - the last gate before work leaves this machine.
#
# This repo lives inside Google Drive and is synced across machines, so the object
# store gets churned. On 2026-08-07 Drive renamed 29 objects to "<name> 2", the drift
# guardrail deleted them as junk, and the repository could no longer reconstruct its
# own history. Recovery was only possible because everything was already on origin.
#
# That is the whole strategy: ORIGIN IS THE BACKUP. A local repo inside Drive is
# expendable as long as it is pushed. This hook makes sure two things are true every
# time you push:
#
#   1. the drift guardrail has run, so renamed originals are restored, not deleted
#   2. git fsck passes, so you are not pushing from a repo that is already damaged
#
# Bypass with --no-verify only if you know exactly why.
set -u
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT" || exit 0

# 1. restore anything Drive renamed, remove genuine duplicates
if [ -x scripts/guardrails/clean-drive-drift.sh ]; then
  if ! scripts/guardrails/clean-drive-drift.sh --fix --quiet; then
    echo "pre-push: drift guardrail reported a problem. Push aborted."
    echo "pre-push: run scripts/guardrails/clean-drive-drift.sh --fix and read the output."
    exit 1
  fi
fi

# 2. refuse to push from a damaged object store
if ! git fsck --connectivity-only --no-progress --no-dangling >/dev/null 2>&1; then
  echo ""
  echo "pre-push: ***** THIS REPOSITORY IS DAMAGED - PUSH ABORTED *****"
  echo ""
  echo "  git fsck cannot walk the object graph. Google Drive has most likely"
  echo "  mangled .git again. Pushing now could publish a broken history."
  echo ""
  echo "  Your committed work is safe on origin. Recover with a fresh clone:"
  echo ""
  echo "    cd \"\$(dirname \"$ROOT\")\""
  echo "    git clone $(git remote get-url origin 2>/dev/null || echo '<origin>') $(basename "$ROOT")-fresh"
  echo ""
  echo "  Then copy across anything gitignored (.env / .dev.vars files, .claude/settings.local.json,"
  echo "  and any local-only folders) before swapping the directories."
  echo ""
  echo "  Do NOT run git gc, git prune or git repack here first. Those turn a"
  echo "  recoverable repository into a lost one."
  echo ""
  exit 1
fi

exit 0
