#!/usr/bin/env bash
# rollback.sh — undo the swap, restore Carbon.
# racked.ru / 2026-05-07
#
# Use ONLY if smoke test fails after a swap. Looks up the most recent backup dir
# created by swap.sh and restores Carbon JAR + configs.

set -euo pipefail

SSH_TARGET="${SSH_TARGET:-user@192.168.0.100}"
CONTAINER="${CONTAINER:-minecraft-mc}"
COMPOSE_DIR="${COMPOSE_DIR:-/opt/docker/minecraft}"
STAGING_DIR="$(cd "$(dirname "$0")/.." && pwd)"

echo "=== STEP 1: locate the most recent chat-swap backup ==="
LATEST=$(ssh "$SSH_TARGET" "docker exec $CONTAINER ls -1 /data/backups | grep ^chat-swap- | sort | tail -1")
echo "  Restoring from: /data/backups/$LATEST"
test -n "$LATEST" || { echo "no backup found, aborting"; exit 1; }

echo ""
echo "=== STEP 2: stop server ==="
ssh "$SSH_TARGET" "cd $COMPOSE_DIR && docker compose stop mc"
sleep 3

echo ""
echo "=== STEP 3: restore Carbon JAR + dir, remove ChatChat ==="
ssh "$SSH_TARGET" "docker run --rm -v minecraft_mc-data:/data alpine:3 sh -c '
  rm -f /data/plugins/ChatChat-*.jar &&
  rm -rf /data/plugins/ChatChat &&
  cp /data/backups/$LATEST/carbonchat-paper-3.0.0-beta.36.jar /data/plugins/ &&
  cp -r /data/backups/$LATEST/CarbonChat /data/plugins/CarbonChat &&
  ls -la /data/plugins | grep -iE \"carbon|chat\"
'"

echo ""
echo "=== STEP 4: roll back LP perms ==="
"${STAGING_DIR}/scripts/lp-rollback.sh" || echo "  (LP rollback partially failed — server is down. Will re-try after boot.)"

echo ""
echo "=== STEP 5: start server ==="
ssh "$SSH_TARGET" "cd $COMPOSE_DIR && docker compose start mc"
sleep 30
ssh "$SSH_TARGET" "docker exec $CONTAINER rcon-cli list"

echo ""
echo "=== STEP 6: re-run LP rollback to ensure clean state ==="
"${STAGING_DIR}/scripts/lp-rollback.sh"

echo ""
echo "=== rollback complete. Carbon should be live again. ==="
