#!/bin/bash

# Define session names
REALMD_SESSION="realmd"
MANGOSD_SESSION="mangosd"

# Define commands and paths
VMANGOS_DIR="/opt/vmangos"
BUILD_DIR="/opt/build"
REALMD_CMD="$VMANGOS_DIR/bin/realmd"
MANGOSD_CMD="$VMANGOS_DIR/bin/mangosd"
LOG_DIR="$VMANGOS_DIR/logs"
REALMD_LOG="$LOG_DIR/realmd.log"
MANGOSD_LOG="$LOG_DIR/mangosd.log"

CONFIG_DIR="$VMANGOS_DIR/etc"
REALMD_CONF="$CONFIG_DIR/realmd.conf"
MANGOSD_CONF="$CONFIG_DIR/mangosd.conf"

start_server() {
    echo "Starting VMaNGOS server..."

    if ! tmux has-session -t $REALMD_SESSION 2>/dev/null; then
        echo "Starting Realmd..."
        tmux new-session -d -s $REALMD_SESSION "$REALMD_CMD | tee $REALMD_LOG"
    else
        echo "Realmd is already running."
    fi

    if ! tmux has-session -t $MANGOSD_SESSION 2>/dev/null; then
        echo "Starting Mangosd..."
        tmux new-session -d -s $MANGOSD_SESSION "$MANGOSD_CMD | tee $MANGOSD_LOG"
    else
        echo "Mangosd is already running."
    fi

    echo "VMaNGOS server started."
}

stop_server() {
    echo "Stopping VMaNGOS server..."

    if tmux has-session -t $MANGOSD_SESSION 2>/dev/null; then
        echo "Sending shutdown command to Mangosd..."
        tmux send-keys -t $MANGOSD_SESSION "server shutdown 3" C-m
        echo "Waiting for server to shut down..."
        sleep 5
        tmux kill-session -t $MANGOSD_SESSION
        echo "Mangosd stopped."
    else
        echo "Mangosd is not running."
    fi

    if tmux has-session -t $REALMD_SESSION 2>/dev/null; then
        echo "Stopping Realmd..."
        tmux kill-session -t $REALMD_SESSION
        echo "Realmd stopped."
    else
        echo "Realmd is not running."
    fi

    echo "VMaNGOS server fully stopped."
}

restart_server() {
    echo "Restarting VMaNGOS server..."
    stop_server
    sleep 2
    start_server
}

attach_console() {
    if [ -n "$2" ]; then
        case "$2" in
            realmd)
                if tmux has-session -t $REALMD_SESSION 2>/dev/null; then
                    tmux attach -t $REALMD_SESSION
                else
                    echo "Realmd is not running."
                    exit 1
                fi
                ;;
            mangosd)
                if tmux has-session -t $MANGOSD_SESSION 2>/dev/null; then
                    tmux attach -t $MANGOSD_SESSION
                else
                    echo "Mangosd is not running."
                    exit 1
                fi
                ;;
            *)
                echo "Invalid session. Use: vmangos attach {realmd|mangosd}"
                exit 1
                ;;
        esac
    else
        # Interactive menu if no session is specified
        echo "Checking available sessions..."
        sessions=()
        if tmux has-session -t $REALMD_SESSION 2>/dev/null; then
            sessions+=("Realmd")
        fi
        if tmux has-session -t $MANGOSD_SESSION 2>/dev/null; then
            sessions+=("Mangosd")
        fi

        if [ ${#sessions[@]} -eq 0 ]; then
            echo "No active VMaNGOS sessions found."
            exit 1
        fi

        echo "Select a session to attach to:"
        select option in "${sessions[@]}" "Cancel"; do
            case $option in
                Realmd) tmux attach -t $REALMD_SESSION ;;
                Mangosd) tmux attach -t $MANGOSD_SESSION ;;
                Cancel) echo "Exiting..."; break ;;
                *) echo "Invalid option. Try again." ;;
            esac
        done
    fi
}

server_status() {
    echo "Checking VMaNGOS server status..."
    if tmux has-session -t $REALMD_SESSION 2>/dev/null; then
        echo "Realmd is running."
    else
        echo "Realmd is NOT running."
    fi

    if tmux has-session -t $MANGOSD_SESSION 2>/dev/null; then
        echo "Mangosd is running."
    else
        echo "Mangosd is NOT running."
    fi

    echo "Checking running processes:"
    pgrep -af "realmd|mangosd"
}

update_server() {
    echo "Updating VMaNGOS server..."

    stop_server
    sleep 2

    echo "Pulling latest updates from GitHub..."
    cd $VMANGOS_DIR/core
    sudo git config pull.rebase false
    sudo git pull

    echo "Recompiling server..."
    cd $BUILD_DIR
    sudo cmake $VMANGOS_DIR/core -DSUPPORTED_CLIENT_BUILD=5875 -DUSE_EXTRACTORS=0 -DCMAKE_INSTALL_PREFIX=$VMANGOS_DIR
    sudo make -j$(nproc) install

    echo "Updating database..."
    cd $VMANGOS_DIR/core/sql/migrations
    ./merge.sh
    mysql -u mangos -pmangos --database=mangos < world_db_updates.sql
    mysql -u mangos -pmangos --database=logs < logs_db_updates.sql
    mysql -u mangos -pmangos --database=characters < characters_db_updates.sql
    mysql -u mangos -pmangos --database=realmd < logon_db_updates.sql

    echo "Server update complete."
    start_server
}

edit_configs() {
    echo "Select a configuration file to edit:"
    options=("Mangosd Config" "Realmd Config" "Cancel")

    select opt in "${options[@]}"; do
        case $opt in
            "Mangosd Config")
                sudo nano "$MANGOSD_CONF"
                break
                ;;
            "Realmd Config")
                sudo nano "$REALMD_CONF"
                break
                ;;
            "Cancel")
                echo "Exiting config editor."
                break
                ;;
            *)
                echo "Invalid option. Try again."
                ;;
        esac
    done
}

case "$1" in
    start) start_server ;;
    stop) stop_server ;;
    restart) restart_server ;;
    attach) attach_console "$@" ;;
    status) server_status ;;
    update) update_server ;;
    configs) edit_configs ;;
    *)
        echo "Usage: $0 {start|stop|restart|attach [realmd|mangosd]|status|update|configs}"
        exit 1
        ;;
esac
