#!/usr/bin/env bash
# rollback.sh — reverse swap.sh: restore EZShop + Kiranhart, drop ExcellentShop
# OPERATOR-ONLY. Run if smoke-test fails after swap.sh.
# Restores the most-recent plugins.tar.bak-* snapshot left by swap.sh.

set -euo pipefail

COMPOSE_DIR=/opt/docker/minecraft
CUSTOM_PLUGIN_DIR=/opt/docker/minecraft-custom-plugins
STAGING_DIR=$(cd "$(dirname "$0")/.." && pwd)

log() { printf '\033[1;33m[rollback %s]\033[0m %s\n' "$(date +%H:%M:%S)" "$*"; }
die() { printf '\033[1;31m[rollback FAIL]\033[0m %s\n' "$*" >&2; exit 1; }

LATEST_BAK=$(sudo ls -1t /opt/docker/minecraft/plugins.tar.bak-* 2>/dev/null | head -1)
[[ -n "$LATEST_BAK" ]] || die "no plugins.tar.bak-* snapshot found in /opt/docker/minecraft/"
log "using snapshot: $LATEST_BAK"

log "1/6: stopping minecraft-mc ..."
sudo docker compose -f "$COMPOSE_DIR/docker-compose.yml" stop mc

log "2/6: removing ExcellentShop + CoinsEngine + nightcore ..."
sudo docker run --rm --privileged --userns=host \
    -v /opt/docker/minecraft:/data \
    docker.io/library/alpine:3 \
    sh -c "rm -rf /data/plugins/ExcellentShop /data/plugins/ExcellentShop-*.jar \
                  /data/plugins/CoinsEngine /data/plugins/CoinsEngine-*.jar \
                  /data/plugins/nightcore /data/plugins/nightcore-*.jar"

log "3/6: clearing custom-plugins bind dir ..."
sudo rm -f "$CUSTOM_PLUGIN_DIR/ExcellentShop-"*.jar \
           "$CUSTOM_PLUGIN_DIR/CoinsEngine-"*.jar \
           "$CUSTOM_PLUGIN_DIR/nightcore-"*.jar

log "4/6: restoring legacy EZShop + AuctionHouse from $LATEST_BAK ..."
sudo docker run --rm --privileged --userns=host \
    -v /opt/docker/minecraft:/data \
    docker.io/library/alpine:3 \
    sh -c "tar -xzf $(basename "$LATEST_BAK") -C /data && cd /data && ls plugins/EZShop plugins/AuctionHouse"

log "5/6: reverting compose (restore most-recent .bak) ..."
LATEST_COMPOSE_BAK=$(ls -1t "$COMPOSE_DIR/docker-compose.yml.bak-"* 2>/dev/null | head -1)
if [[ -n "$LATEST_COMPOSE_BAK" ]]; then
    cp "$LATEST_COMPOSE_BAK" "$COMPOSE_DIR/docker-compose.yml"
    log "  restored compose: $LATEST_COMPOSE_BAK"
fi

log "6/6: starting minecraft-mc + reverse-LP migration ..."
sudo docker compose -f "$COMPOSE_DIR/docker-compose.yml" up -d mc

deadline=$(( $(date +%s) + 240 ))
until sudo docker exec minecraft-mc mc-health 2>/dev/null; do
    [[ $(date +%s) -gt $deadline ]] && die "server did not come healthy in 4 minutes"
    sleep 5
done

sudo docker exec -i minecraft-mc bash -s < "$STAGING_DIR/scripts/lp-shop-rollback.sh"

log "DONE. Verify /shop and /ah are back to legacy behaviour."
