#!/usr/bin/env bash
# swap.sh — racked.ru EZShop+Kiranhart -> ExcellentShop+CoinsEngine swap
#
# OPERATOR-ONLY. Run on nullstone (192.168.0.100) as `user`.
# This script DOES restart the minecraft container. Schedule a 30-minute
# maintenance window before invoking.
#
# Pre-flight (manual, before this script):
#   1. Announce 1-week then 1-day then 1-hour heads-up via /pm news.
#   2. Drain or expire all active Kiranhart AH listings (refund stuck items).
#   3. Snapshot /opt/docker/minecraft via restic (see scripts/restic-backup-playerdata.sh).
#   4. Confirm the staged jars are present and checksums match the bundle on disk.
#
# Post-flight (manual, after this script):
#   1. /shop -- verify the main category menu opens, 11 shops visible.
#   2. /ah    -- verify auction house opens, listing flow works (test admin item).
#   3. /sellall -- run with a test stack, verify CoinsEngine balance updated.
#   4. /balance -- verify EssentialsX/Vault still resolves through CoinsEngine.
#   5. Smoke-test a non-staff player join: shop perms, listing perms.
#   6. Tail logs for `nightcore` and `excellentshop` errors for ~5 minutes.

set -euo pipefail

COMPOSE_DIR=/opt/docker/minecraft
PLUGIN_DIR=/opt/docker/minecraft/plugins
CUSTOM_PLUGIN_DIR=/opt/docker/minecraft-custom-plugins
STAGING_DIR=$(cd "$(dirname "$0")/.." && pwd)
TS=$(date +%Y%m%d-%H%M%S)

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

[[ -d "$STAGING_DIR/build" ]] || die "staging build dir missing: $STAGING_DIR/build"
for j in ExcellentShop-5.0.1.jar CoinsEngine-2.7.0.jar nightcore-2.15.3.jar; do
    [[ -f "$STAGING_DIR/build/$j" ]] || die "missing jar: $j"
done

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

log "2/8: backing up old plugin tree to /opt/docker/minecraft.bak-$TS ..."
sudo docker run --rm --privileged --userns=host \
    -v /opt/docker/minecraft:/data \
    docker.io/library/alpine:3 \
    sh -c "tar -czf /data/plugins.tar.bak-$TS -C /data plugins/EZShop plugins/EZShop-1.0-SNAPSHOT.jar plugins/AuctionHouse plugins/AuctionHouse-1.4.6.jar 2>/dev/null || true"

log "3/8: removing legacy EZShop + AuctionHouse ..."
sudo docker run --rm --privileged --userns=host \
    -v /opt/docker/minecraft:/data \
    docker.io/library/alpine:3 \
    sh -c "rm -rf /data/plugins/EZShop /data/plugins/EZShop-*.jar /data/plugins/AuctionHouse /data/plugins/AuctionHouse-*.jar"

log "4/8: ensuring custom-plugins bind dir exists ..."
sudo mkdir -p "$CUSTOM_PLUGIN_DIR"
sudo cp "$STAGING_DIR/build/"*.jar "$CUSTOM_PLUGIN_DIR/"
sudo chown -R 1000:1000 "$CUSTOM_PLUGIN_DIR"
ls -la "$CUSTOM_PLUGIN_DIR"

log "5/8: applying compose patch (custom plugins bind + EXCLUDE list) ..."
if ! grep -q "minecraft-custom-plugins" "$COMPOSE_DIR/docker-compose.yml"; then
    cp "$COMPOSE_DIR/docker-compose.yml" "$COMPOSE_DIR/docker-compose.yml.bak-$TS"
    sudo cp "$STAGING_DIR/scripts/docker-compose.patch.yml" "$COMPOSE_DIR/docker-compose.yml"
fi

log "6/8: starting minecraft-mc (first start will create configs) ..."
sudo docker compose -f "$COMPOSE_DIR/docker-compose.yml" up -d mc

log "7/8: waiting for server to be healthy (max 4 min) ..."
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

log "8/8: applying staged config overrides + LP perms ..."
# copy staged configs into the now-populated plugin tree
sudo docker cp "$STAGING_DIR/configs/excellentshop/config.yml" minecraft-mc:/data/plugins/ExcellentShop/config.yml
sudo docker cp "$STAGING_DIR/configs/excellentshop/modules/virtual_shop/config.yml" minecraft-mc:/data/plugins/ExcellentShop/modules/virtual_shop/config.yml
sudo docker cp "$STAGING_DIR/configs/excellentshop/modules/auction/config.yml" minecraft-mc:/data/plugins/ExcellentShop/modules/auction/config.yml
sudo docker cp "$STAGING_DIR/configs/coinsengine/config.yml" minecraft-mc:/data/plugins/CoinsEngine/config.yml
sudo docker cp "$STAGING_DIR/configs/coinsengine/currencies/coin.yml" minecraft-mc:/data/plugins/CoinsEngine/currencies/coin.yml
sudo docker exec minecraft-mc rcon-cli excellentshop reload || true
sudo docker exec minecraft-mc rcon-cli coinsengine reload || true

# LP perms migration
sudo docker exec -i minecraft-mc bash -s < "$STAGING_DIR/scripts/lp-shop-migration.sh"

log "DONE. Verify in-game now:"
log "  /shop      <- main category menu"
log "  /ah        <- auction house"
log "  /sellall   <- bulk sell"
log "  /balance   <- CoinsEngine via Vault"
log ""
log "If anything is broken, run: $STAGING_DIR/scripts/rollback.sh"
