#!/bin/bash
# Auto-sync: pull, stage, vault-verify (gated), commit, push. Runs every 30 min.
set -u
cd /home/ccuser/rateright-growth || exit 1

# 0. PREFLIGHT GUARD (added 2026-06-11 after 5-week detached-HEAD incident)
# Never touch the repo if a rebase/merge is mid-flight or HEAD is detached.
# Silently committing onto a detached HEAD is what broke sync for 5 weeks.
halt() {
  echo "[$(date)] AUTOSYNC HALTED -- $1" | tee -a logs/auto-sync.log
  echo "[$(date)] $1" > logs/AUTOSYNC-HALTED.flag
  exit 1
}
[ -d .git/rebase-merge ] && halt "rebase-merge in progress"
[ -d .git/rebase-apply ] && halt "rebase-apply in progress"
[ -f .git/MERGE_HEAD ]   && halt "merge in progress (MERGE_HEAD)"
git symbolic-ref -q HEAD >/dev/null || halt "HEAD is detached (not on a branch)"
# Clear any stale halt flag now that preflight passed
rm -f logs/AUTOSYNC-HALTED.flag

# 1. Pull first to avoid conflicts (VPS wins via rebase)
git pull --rebase --autostash 2>/dev/null
# Post-pull: pull --rebase can stop mid-rebase on conflict; detect + halt.
[ -d .git/rebase-merge ] && halt "pull --rebase stopped mid-rebase (conflict) -- manual fix needed"

# 2. Stage everything except secrets
git add -A
git reset -- .env .env.* secrets.json **/secrets.json 2>/dev/null

CHANGED=$(git diff --cached --name-only)

if [ -z "$CHANGED" ]; then
  echo "[$(date)] Nothing to sync"
  exit 0
fi

# 3. Vault-verify gate — only run if HQ-Vault content was touched
if echo "$CHANGED" | grep -q "^HQ-Vault/"; then
  if ! python3 scripts/vault-verify.py > /tmp/vault-verify.log 2>&1; then
    echo "[$(date)] VAULT VERIFY FAILED — aborting commit. Tail of /tmp/vault-verify.log:"
    tail -20 /tmp/vault-verify.log | sed "s/^/  /"
    # Unstage vault changes so non-vault changes can still ship next cycle
    git restore --staged HQ-Vault/ 2>/dev/null
    # Re-check — if there is still non-vault content staged, proceed
    REMAINING=$(git diff --cached --name-only)
    if [ -z "$REMAINING" ]; then
      exit 1
    fi
    echo "[$(date)] vault changes unstaged; non-vault changes will still commit"
  fi
fi

# 3b. Append-only gate — block any modification that removes lines from
# append-only files (daily notes, _Log.md, _AgentLog/, CuratorLog, Conflicts).
if ! bash scripts/check-append-only.sh 2>/tmp/append-only.log; then
  echo "[$(date)] APPEND-ONLY VIOLATION — aborting commit. See /tmp/append-only.log:"
  sed "s/^/  /" /tmp/append-only.log
  # Unstage the offending files so the next cycle can retry once corrected
  git diff --cached --name-only --diff-filter=M | \
    grep -E 'HQ-Vault/01_Daily/.*\.md$|HQ-Vault/.+/_Log\.md$|HQ-Vault/.+/_AgentLog/.*\.md$|HQ-Vault/_System/CuratorLog\.md$|HQ-Vault/_System/Conflicts\.md$' | \
    xargs -r git restore --staged
  REMAINING=$(git diff --cached --name-only)
  if [ -z "$REMAINING" ]; then
    exit 1
  fi
  echo "[$(date)] append-only-violating changes unstaged; remaining changes will still commit"
fi

# 4. Commit + push
git commit -m "auto-sync: $(date +%Y-%m-%d\ %H:%M)"
git push
echo "[$(date)] Synced: $(git log --oneline -1)"
