#!/bin/bash

set -e

cd /home/container || {
    echo "ERROR: /home/container does not exist"
    exit 1
}

# Install if needed
if [[ "$BL_INST_FORCE" == "1" ]] || [ ! -f "Blockland.exe" ]; then
    source /usr/local/bin/install-bl
fi

# Required vars
[ -z "$BL_PORT" ] && echo "Missing BL_PORT" && exit 1
[ -z "$BL_GAMEMODE" ] && echo "Missing BL_GAMEMODE" && exit 1

if [[ "$BL_DEDI_LAN" == "1" ]]; then
    dedi="dedicatedLAN"
else
    [ -z "$BL_DTOKEN" ] && echo "Missing BL_DTOKEN" && exit 1
    dedi="dedicated"
fi

# Create wine prefix if missing
if [ ! -d "$HOME/.wine" ]; then
    echo "Creating wine prefix..."
    wineboot -i
    sleep 3
fi

if [ "${BL_UNZIP_ADDONS:-0}" -eq 1 ]; then
    echo "Processing Add-Ons zips..."

    cd /home/container/Add-Ons || exit 1

    for zip in *.zip; do
        [ -f "$zip" ] || continue

        addon_name="${zip%.zip}"

        echo "Extracting $zip..."

        # Extract into a temp directory first
        mkdir -p "__tmp_extract__"
        unzip -o "$zip" -d "__tmp_extract__" >/dev/null

        # Count top-level items in extraction
        item_count=$(find "__tmp_extract__" -mindepth 1 -maxdepth 1 | wc -l)

        if [ "$item_count" -eq 1 ]; then
            first_item=$(find "__tmp_extract__" -mindepth 1 -maxdepth 1)

            if [ -d "$first_item" ]; then
                # Proper folder structure, just move it
                mv "$first_item" .
            else
                # Single loose file — fix structure
                mkdir -p "$addon_name"
                mv "$first_item" "$addon_name"/
            fi
        else
            # Multiple loose files — put them in folder
            mkdir -p "$addon_name"
            mv "__tmp_extract__"/* "$addon_name"/
        fi

        rm -rf "__tmp_extract__"
        rm -f "$zip"
    done
fi

# Sync Add-On from git repository if BL_ADDON_REPO is set (only on reboot; only pulls when remote has updates)
if [ -n "$BL_ADDON_REPO" ]; then
    echo "Syncing Add-On from git repository..."

    mkdir -p /home/container/Add-Ons
    cd /home/container/Add-Ons

    repo_name=$(basename "$BL_ADDON_REPO" .git)

    if [ -d "$repo_name/.git" ]; then
        cd "$repo_name"
        git fetch origin
        upstream=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)
        behind=$(git rev-list HEAD.."${upstream:-origin/HEAD}" --count 2>/dev/null || echo 0)
        if [ "${behind:-0}" -gt 0 ]; then
            echo "Add-On has updates, pulling..."
            git pull --ff-only
        else
            echo "Add-On is up to date."
        fi
        cd /home/container/Add-Ons
    else
        clone_opts=()
        [ -n "$BL_ADDON_REPO_BRANCH" ] && clone_opts=(-b "$BL_ADDON_REPO_BRANCH")
        git clone "${clone_opts[@]}" "$BL_ADDON_REPO"
    fi

    cd /home/container || exit 1
fi

# Ensure we're in the correct directory (server root where Blockland.exe lives)
cd /home/container || exit 1

if [ ! -f "Blockland.exe" ]; then
    echo "Blockland.exe not found!"
    exit 1
fi

echo "Launching Blockland..."

server_name_args=()
[ -n "$BL_SERVER_NAME" ] && server_name_args=(-serverName "$BL_SERVER_NAME")

max_players_args=()
[ -n "$BL_MAX_PLAYERS" ] && max_players_args=(-maxPlayers "$BL_MAX_PLAYERS")

exec xvfb-run -a wine "Blockland.exe" \
    ptlaaxobimwroe \
    -${dedi} \
    -port "$BL_PORT" \
    -dtoken "$BL_DTOKEN" \
    -gamemode "$BL_GAMEMODE" \
    "${server_name_args[@]}" \
    "${max_players_args[@]}" \
    $BL_EXTRA_ARGS