#!/bin/bash

set -e

cd /data

if [[ "$BL_INST_FORCE" -eq 1 ]] || [ ! -f "Blockland.exe" ]; then
    source "install-bl"
fi

if [ -z "$BL_PORT" ]; then
    echo "Please provide a port by setting BL_PORT"
    exit -1
fi

if [ -z "$BL_GAMEMODE" ]; then
    echo "Please provide a gamemode by setting BL_GAMEMODE"
    exit -1
fi

if [ -z "$BL_SERVER_NAME" ]; then
    echo "Please provide a server name by setting BL_SERVER_NAME"
    exit -1
fi

if [[ "$BL_MAX_PLAYERS" -lt 1 ]]; then
    echo "BL_MAX_PLAYERS must be greater than 0"
    exit -1
fi

if [[ "$BL_DEDI_LAN" -eq 0 ]]; then
    if [ -z "$BL_DTOKEN" ]; then
        echo "Please provide a dtoken by setting BL_DTOKEN"
        exit -1
    fi

    dedi=dedicated
else
    dedi=dedicatedLAN
fi

unset DISPLAY

# If the wine prefix doesn't exist, create it using wineboot
# rather than having it be created by launching Blockland,
# as Blockland will hang otherwise.
if [ ! -d "$HOME/.wine" ]; then
    echo "Creating wine prefix..."
    wineboot -i

    # Annoyingly, if Blockland is launched too quickly after wineboot,
    # CreateWindowExA fails which means winsockWindow in winNet.cc@184
    # in TGE is set to NULL.  This causes all networking in Blockland
    # to not function correctly, as WinsockProc will not be called.
    echo "Waiting for wine to fully init..."
    sleep 3
fi

echo "Launching Blockland..."
xvfb-run  -a wine "Blockland.exe" ptlaaxobimwroe -${dedi} -port $BL_PORT -dtoken $BL_DTOKEN -gamemode $BL_GAMEMODE -serverName $BL_SERVER_NAME -maxPlayers $BL_MAX_PLAYERS $BL_EXTRA_ARGS
