#!/bin/bash
# One-time setup: prepare the bare mirror repo for teleo-infrastructure.
#
# Prerequisites (must happen BEFORE running this):
#   1. GitHub repo `living-ip/teleo-infrastructure` created (manual via web or
#      `gh repo create` — the deploy PAT is fine-grained to teleo-codex only
#      and cannot create new repos in the org).
#   2. GitHub PAT updated to include push access on the new repo (or rotate
#      to a classic PAT with `repo` scope covering both).
#
# This script is idempotent — safe to re-run.

set -euo pipefail

MIRROR_BASE="/opt/teleo-eval/mirror"
REPO_DIR="$MIRROR_BASE/teleo-infrastructure.git"
FORGEJO_URL="http://localhost:3000/teleo/teleo-infrastructure.git"
GITHUB_REPO="living-ip/teleo-infrastructure"
FORGEJO_TOKEN_FILE="/opt/teleo-eval/secrets/forgejo-admin-token"
GITHUB_PAT_FILE="/opt/teleo-eval/secrets/github-pat"

if [ ! -f "$FORGEJO_TOKEN_FILE" ]; then
    echo "ERROR: missing $FORGEJO_TOKEN_FILE" >&2
    exit 1
fi
if [ ! -f "$GITHUB_PAT_FILE" ]; then
    echo "ERROR: missing $GITHUB_PAT_FILE" >&2
    exit 1
fi

FORGEJO_TOKEN=$(cat "$FORGEJO_TOKEN_FILE" | tr -d '[:space:]')
GITHUB_PAT=$(cat "$GITHUB_PAT_FILE" | tr -d '[:space:]')

# Sanity check: GitHub repo must exist before we point a remote at it.
echo "Verifying GitHub repo $GITHUB_REPO exists..."
GH_STATUS=$(curl -sS -o /dev/null -w "%{http_code}" \
    -H "Authorization: Bearer $GITHUB_PAT" \
    "https://api.github.com/repos/$GITHUB_REPO")
if [ "$GH_STATUS" != "200" ]; then
    echo "ERROR: GitHub repo $GITHUB_REPO not accessible (HTTP $GH_STATUS)" >&2
    echo "Create it first: gh repo create $GITHUB_REPO --public --description 'Pipeline + diagnostics infra for the LivingIP collective'" >&2
    exit 2
fi
echo "  OK — $GITHUB_REPO accessible"

# Sanity check: Forgejo repo must exist.
echo "Verifying Forgejo repo teleo/teleo-infrastructure exists..."
FG_STATUS=$(curl -sS -o /dev/null -w "%{http_code}" \
    -H "Authorization: token $FORGEJO_TOKEN" \
    "http://localhost:3000/api/v1/repos/teleo/teleo-infrastructure")
if [ "$FG_STATUS" != "200" ]; then
    echo "ERROR: Forgejo repo teleo/teleo-infrastructure not accessible (HTTP $FG_STATUS)" >&2
    exit 3
fi
echo "  OK — Forgejo repo accessible"

# Init bare mirror if missing
if [ -d "$REPO_DIR" ]; then
    echo "Bare repo already exists at $REPO_DIR — skipping init"
else
    echo "Creating bare repo at $REPO_DIR..."
    mkdir -p "$REPO_DIR"
    cd "$REPO_DIR"
    git init --bare >/dev/null
    chown -R teleo:teleo "$REPO_DIR"
    echo "  OK — bare repo initialized"
fi

cd "$REPO_DIR"

# Configure remotes (idempotent: set-url succeeds whether remote exists or not)
# Forgejo remote (origin convention is reversed in this codebase: origin=GitHub,
# forgejo=Forgejo, matching the existing teleo-codex.git layout).
FORGEJO_REMOTE_URL="http://github-mirror:${FORGEJO_TOKEN}@localhost:3000/teleo/teleo-infrastructure.git"
# NOTE: "m3taversal" is a placeholder username — for fine-grained PATs the
# username field is decorative; the token does the auth. Matches the existing
# teleo-codex.git remote for consistency. (Ganymede review nit #4.)
GITHUB_REMOTE_URL="https://m3taversal:${GITHUB_PAT}@github.com/${GITHUB_REPO}.git"

if git remote get-url forgejo >/dev/null 2>&1; then
    git remote set-url forgejo "$FORGEJO_REMOTE_URL"
    echo "  Updated forgejo remote URL"
else
    git remote add forgejo "$FORGEJO_REMOTE_URL"
    echo "  Added forgejo remote"
fi

if git remote get-url origin >/dev/null 2>&1; then
    git remote set-url origin "$GITHUB_REMOTE_URL"
    echo "  Updated origin remote URL"
else
    git remote add origin "$GITHUB_REMOTE_URL"
    echo "  Added origin remote"
fi

# Initial fetch from Forgejo
echo "Fetching from Forgejo..."
git fetch forgejo --prune 2>&1 | sed 's/^/  /'

# Initial push to GitHub (will populate the empty repo)
# main_only mode: push ONLY refs/heads/main + tags, mirroring what sync-mirror.sh
# does for this repo on the recurring path. Agent review branches stay Forgejo-only.
echo "Pushing initial main + tags to GitHub..."
git update-ref refs/heads/main refs/remotes/forgejo/main 2>/dev/null || {
    echo "ERROR: forgejo/main ref missing — fetch may have failed" >&2
    exit 1
}

git push origin "refs/heads/main:refs/heads/main" 2>&1 | sed 's/^/  /' || {
    echo "WARN: initial push failed — you may need to authorize the PAT for $GITHUB_REPO" >&2
}
git push origin --tags 2>&1 | sed 's/^/  /' || true

# Final permissions sweep
chown -R teleo:teleo "$REPO_DIR"

echo
echo "Setup complete. Verify with:"
echo "  ssh teleo@77.42.65.182 ls -la $REPO_DIR/refs/heads"
echo "  /opt/teleo-eval/sync-mirror.sh && tail -50 /opt/teleo-eval/logs/sync.log"
