#!/bin/bash
# =============================================================================
# promote.sh
# Flips the watcher from TEST repo → kenpat/kitestacks-homelab (main).
# Run after verifying the test repo looks correct in Forgejo.
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/config/settings.conf"
STATE_FILE="/opt/kitestacks-autosync/.active_target"
WORK_DIR="/opt/kitestacks-autosync"

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC}  $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

[[ $EUID -ne 0 ]] && error "Run as root: sudo bash promote.sh"
source "$CONFIG_FILE"

CURRENT="$(cat "$STATE_FILE" 2>/dev/null || echo "test")"
if [[ "$CURRENT" == "main" ]]; then
    warn "Already targeting kenpat/kitestacks-homelab. Nothing to do."
    exit 0
fi

echo ""
warn "┌──────────────────────────────────────────────────────────────┐"
warn "│  PROMOTE: test repo → kenpat/kitestacks-homelab              │"
warn "│                                                               │"
warn "│  From: ${FORGEJO_URL}/${FORGEJO_USER}/${TEST_REPO}"
warn "│  To  : ${FORGEJO_URL}/${FORGEJO_USER}/${MAIN_REPO}"
warn "│                                                               │"
warn "│  All future auto-commits will go to the MAIN repo.           │"
warn "└──────────────────────────────────────────────────────────────┘"
echo ""
read -rp "Have you verified the test repo looks correct? Type 'promote' to confirm: " CONFIRM
[[ "$CONFIRM" != "promote" ]] && { info "Aborted."; exit 0; }

# ── Set up remote prefix ──────────────────────────────────────────────────────
if [[ "$AUTH_METHOD" == "ssh" ]]; then
    REMOTE_BASE="git@gitforge.kitestacks.com:${FORGEJO_USER}"
else
    REMOTE_BASE="https://gitforge.kitestacks.com/${FORGEJO_USER}"
fi

# ── Clone main repo if not already present ────────────────────────────────────
MAIN_DIR="$WORK_DIR/$MAIN_REPO"
if [[ ! -d "$MAIN_DIR/.git" ]]; then
    info "Cloning kenpat/kitestacks-homelab..."
    git clone "${REMOTE_BASE}/${MAIN_REPO}.git" "$MAIN_DIR"
fi

cd "$MAIN_DIR"
git config user.email "$GIT_EMAIL"
git config user.name  "$GIT_NAME"
git pull --rebase origin HEAD 2>/dev/null || true

# ── Add version tag to main README.md if not already there ───────────────────
if ! grep -q '<!-- version:' "$MAIN_DIR/README.md" 2>/dev/null; then
    info "Injecting version tag into main README.md..."

    # Get the latest version from the test repo
    TEST_VER=$(grep -oP '(?<=version:\s)[\d.]+' "$WORK_DIR/$TEST_REPO/README.md" 2>/dev/null | head -1 || echo "1.3.0")

    # Inject after the first H1
    sed -i "0,/^# /{s|^# \(.*\)|# \1\n\n<!-- version: $TEST_VER -->|}" "$MAIN_DIR/README.md"

    # Update the docs reference line
    sed -i "s|docs/KiteStacks-Homelab-Documentation-v.*\.md|docs/KiteStacks-Homelab-Documentation-v${TEST_VER}.md|" "$MAIN_DIR/README.md" || true

    # Copy CHANGELOG.md and docs from test repo if main doesn't have them
    if [[ ! -f "$MAIN_DIR/CHANGELOG.md" ]]; then
        cp "$WORK_DIR/$TEST_REPO/CHANGELOG.md" "$MAIN_DIR/CHANGELOG.md" 2>/dev/null || true
    fi
    if [[ ! -d "$MAIN_DIR/docs" ]]; then
        cp -r "$WORK_DIR/$TEST_REPO/docs" "$MAIN_DIR/docs" 2>/dev/null || true
    fi

    git add -A
    git commit -m "chore: inject autosync version tracking — promoted from test"
    git push origin HEAD
    info "Main repo prepared for autosync."
fi

# ── Flip state ────────────────────────────────────────────────────────────────
echo "main" > "$STATE_FILE"
info "Active target → main (kenpat/kitestacks-homelab)"

# ── Restart service ───────────────────────────────────────────────────────────
info "Restarting kitestacks-autosync service..."
systemctl restart kitestacks-autosync
sleep 2
systemctl status kitestacks-autosync --no-pager

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
info "Promotion complete!"
info "  Now watching → ${FORGEJO_URL}/${FORGEJO_USER}/${MAIN_REPO}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
