#!/bin/bash
# Bestiaire.app's launcher: the game data on first run, the Bestiaire addon, the nearest server,
# then the benilla client. Everything the game keeps lives in ~/Library/Application Support/Bestiaire.
set -u

HERE="$(cd "$(dirname "$0")" && pwd)"
RES="$HERE/../Resources"
SUPPORT="$HOME/Library/Application Support/Bestiaire"
DATA_DIR="$SUPPORT/wow-data"
DATA="$DATA_DIR/Data"
CONFIG="$SUPPORT/config"
# The server: at home, the homelab VM over the LAN; elsewhere, its public name. server.txt in the
# support folder overrides both (one host name or address per line, tried in order).
SERVERS=(192.168.1.120 wow.axel-mitschi.com)
if [ -f "$SUPPORT/server.txt" ]; then
    SERVERS=()
    while IFS= read -r line; do SERVERS+=("$line"); done < "$SUPPORT/server.txt"
fi

mkdir -p "$CONFIG/AddOns"

# The game data: a WoW 1.12.1 client's Data folder, downloaded once (~5.5 GB) in a Terminal window
# so the progress shows. A data folder from an earlier install is reused instead.
if [ ! -f "$DATA/terrain.MPQ" ] || [ ! -f "$DATA/patch.MPQ" ]; then
    for old in "$HOME/echelle/wow-data/Data" "$HOME/wow-data/Data"; do
        if [ -f "$old/terrain.MPQ" ]; then
            mkdir -p "$DATA_DIR"
            ln -sfn "$old" "$DATA"
            break
        fi
    done
fi
if [ ! -f "$DATA/terrain.MPQ" ] || [ ! -f "$DATA/patch.MPQ" ]; then
    osascript -e 'display dialog "Premier lancement : Bestiaire va télécharger les données du jeu (environ 5,5 Go). Une fenêtre Terminal montre la progression ; le jeu se lancera tout seul à la fin." buttons {"OK"} default button 1 with title "Bestiaire"' >/dev/null
    osascript -e "tell application \"Terminal\" to do script \"bash '$RES/fetch-data.sh' '$DATA_DIR' && open -a '$(cd "$HERE/../.." && pwd)'; exit\"" >/dev/null
    exit 0
fi

# The addon always comes from the app, so an updated app updates it.
rm -rf "$CONFIG/AddOns/Bestiaire"
cp -R "$RES/AddOns/Bestiaire" "$CONFIG/AddOns/Bestiaire"

# The first server whose login port answers.
HOST="${SERVERS[${#SERVERS[@]}-1]}"
for s in "${SERVERS[@]}"; do
    [ -z "$s" ] && continue
    if nc -z -G 2 "$s" 3724 >/dev/null 2>&1; then
        HOST="$s"
        break
    fi
done

export BENILLA_HOME="$CONFIG" WOW_DATA="$DATA" WOW_HOST="$HOST"
exec "$HERE/benilla"
