#!/usr/bin/env bash
#

set -e

readonly BASE_DIR="$(realpath "$(dirname "${0}")/..")"
source "${BASE_DIR}/.env"

# Nom du conteneur Docker
CONTAINER="wow-mangosd"

function create_realm() {
    local REALM_NAME="${1}"
    local REALM_ADDRESS="${2}"

    # Variables fixes
    REALM_ID=1
    REALM_PORT=8085

    echo "⚙️  Configuration du realm '$REALM_NAME' ($REALM_ADDRESS:$REALM_PORT)..."

    # Exécution des requêtes SQL via un client mysql externe
    docker run --rm -i \
        --network container:$CONTAINER \
        mysql:5.7 \
        mysql -hdatabase -u$MANGOS_DBUSER -p$MANGOS_DBPASS ${WOW_VERSION}realmd <<EOF
DELETE FROM realmlist WHERE id = $REALM_ID;

INSERT INTO realmlist (id, name, address, port, icon, realmflags, timezone, allowedSecurityLevel)
VALUES ('$REALM_ID', '$REALM_NAME', '$REALM_ADDRESS', '$REALM_PORT', '1', '0', '8', '0');
EOF

    echo "✅ Realm '$REALM_NAME' avec IP '$REALM_ADDRESS' a été configuré."
}

# function create_account() {
#     local ACCOUNT_NAME="${1}"
#     local ACCOUNT_PASS="${2}"
#     local GMLEVEL="${3:-0}"

#     echo "⚙️  Création du compte '$ACCOUNT_NAME' (GM level $GMLEVEL)..."

#     # Création via le binaire mangosd dans le conteneur
#     docker exec -i $CONTAINER /opt/mangos/bin/realmd account create "$ACCOUNT_NAME" "$ACCOUNT_PASS -c /opt/mangos/conf/realmd.conf"
#     docker exec -i $CONTAINER /opt/mangos/bin/realmd account set gmlevel "$ACCOUNT_NAME" "$GMLEVEL" -1 "-c /opt/mangos/conf/realmd.conf"
#     # Attribution du GM level si nécessaire
#     if [ "$GMLEVEL" -gt 0 ]; then
#         docker exec -i $CONTAINER /opt/mangos/bin/mangosd account set gmlevel "$ACCOUNT_NAME" "$GMLEVEL" -1
#     fi

#     echo "✅ Compte '$ACCOUNT_NAME' créé avec succès (GM level $GMLEVEL)."
# }

case "${1}" in
    create_realm)
        shift
        create_realm "${@}"
        ;;
    create_account)
        shift
        create_account "${@}"
        ;;
    *)
        cd "${HOME_DIR}"
        exec "${@}"
        ;;
esac
