#!/bin/bash
# hermes-sync — keep sovereign fork current with upstream
#
# Usage:
#   hermes-sync          # pull upstream, rebase sovereign patches on top
#   hermes-sync push     # also push to Gitea after rebase
#   hermes-sync config   # commit + push config changes
#   hermes-sync status   # show both repos' status
#
set -euo pipefail

HERMES_HOME="$HOME/.hermes"
AGENT_DIR="$HERMES_HOME/hermes-agent"

case "${1:-rebase}" in

  rebase)
    echo "═══ Syncing hermes-agent with upstream ═══"
    cd "$AGENT_DIR"
    git fetch upstream
    echo "→ Rebasing sovereign onto upstream/main..."
    git rebase upstream/main
    echo "✅ Sovereign branch rebased. Run 'hermes-sync push' to push to Gitea."
    ;;

  push)
    echo "═══ Syncing hermes-agent with upstream + push ═══"
    cd "$AGENT_DIR"
    git fetch upstream
    echo "→ Rebasing sovereign onto upstream/main..."
    git rebase upstream/main
    echo "→ Force-pushing sovereign to Gitea..."
    git push origin sovereign --force-with-lease
    echo "→ Updating main mirror..."
    git checkout main
    git pull upstream main
    git push origin main
    git checkout sovereign
    echo "✅ Both branches synced to Gitea."
    ;;

  config)
    echo "═══ Committing hermes config changes ═══"
    cd "$HERMES_HOME"
    git add -A
    if git diff --cached --quiet; then
      echo "No config changes to commit."
    else
      git commit -m "update: $(date +%Y-%m-%d) config sync"
      git push origin main
      echo "✅ Config pushed to Gitea."
    fi
    ;;

  status)
    echo "═══ hermes-agent (sovereign fork) ═══"
    cd "$AGENT_DIR"
    git log --oneline -3
    echo ""
    git status --short | head -10
    AHEAD=$(git rev-list upstream/main..sovereign --count 2>/dev/null || echo "?")
    BEHIND=$(git rev-list sovereign..upstream/main --count 2>/dev/null || echo "?")
    echo ""
    echo "Patches ahead of upstream: $AHEAD"
    echo "Commits behind upstream:   $BEHIND"
    echo ""
    echo "═══ hermes-config ═══"
    cd "$HERMES_HOME"
    git log --oneline -3
    echo ""
    git status --short | head -10
    ;;

  *)
    echo "Usage: hermes-sync [rebase|push|config|status]"
    exit 1
    ;;
esac
