#!/bin/bash
# Manage whitelists across all Minecraft servers on CT 644
# Usage: ./whitelist.sh add <username>
#        ./whitelist.sh remove <username>
#        ./whitelist.sh list

ACTION="$1"
PLAYER="$2"

SERVERS=(
    "mc1|25575|REDACTED_RCON"
    "shrink-world|25576|REDACTED_RCON"
    "paper-ai|25577|REDACTED_RCON"
)

rcon_cmd() {
    local port="$1" pass="$2" cmd="$3"
    ssh pve112 "pct exec 644 -- python3 -c \"
from mcrcon import MCRcon
with MCRcon('localhost', '$pass', port=$port) as r:
    print(r.command('$cmd'))
\"" 2>/dev/null
}

case "$ACTION" in
    add)
        [ -z "$PLAYER" ] && echo "Usage: $0 add <username>" && exit 1
        for s in "${SERVERS[@]}"; do
            IFS='|' read -r name port pass <<< "$s"
            echo -n "$name: "
            rcon_cmd "$port" "$pass" "whitelist add $PLAYER"
        done
        ;;
    remove)
        [ -z "$PLAYER" ] && echo "Usage: $0 remove <username>" && exit 1
        for s in "${SERVERS[@]}"; do
            IFS='|' read -r name port pass <<< "$s"
            echo -n "$name: "
            rcon_cmd "$port" "$pass" "whitelist remove $PLAYER"
        done
        ;;
    list)
        for s in "${SERVERS[@]}"; do
            IFS='|' read -r name port pass <<< "$s"
            echo -n "$name: "
            rcon_cmd "$port" "$pass" "whitelist list"
        done
        ;;
    *)
        echo "Usage: $0 {add|remove|list} [username]"
        exit 1
        ;;
esac
