#!/bin/bash
# Launch the Zimarus/Tanarus 2002 client under Proton, outside the Steam client.
# Portable cut-down of the developer's proton_tanarus.sh (Ubuntu, verified daily).
#
#   bash Tanarus_Linux.sh                                  # from inside the game folder
#   bash Tanarus_Linux.sh <game-folder> [online|offline]   # from anywhere (default online)
#
# Latest copy: https://tan.zimmey.com/downloads/Tanarus_Linux.sh
# Instructions: https://tan.zimmey.com/linux.php  (also README-LINUX.txt)
#
#   TANARUS_PROTON="Proton - Experimental"   pick a runtime by folder name (default: newest
#                                            GE-Proton found, else Proton Experimental)
#   TANARUS_WINDOWED=1                       Wine virtual desktop instead of exclusive
#                                            fullscreen (alt-tab-safe, mouse-only in arena)
#   TANARUS_PFX=/path                        prefix location (default ~/.local/share/zimarus-pfx-<runtime>)
#
# Hard rules (from the game's own code): the exe path must contain NO spaces, and the
# argument must follow the exe after exactly one space — proton/wine's argv join does that.
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
if [ -n "${1:-}" ] && [ -d "$1" ]; then GAME_DIR="$1"; shift; else GAME_DIR="$HERE"; fi
case "${1:-online}" in online|offline) MODE="${1:-online}";; *) echo "usage: $0 [<game-folder>] [online|offline]"; exit 1;; esac
GAME_DIR="$(cd "$GAME_DIR" && pwd)"
[ -f "$GAME_DIR/tangame.exe" ] || { echo "no tangame.exe in $GAME_DIR — run this from the game folder or pass its path"; exit 1; }
case "$GAME_DIR" in *" "*) echo "install path contains a space — the game will refuse to start: $GAME_DIR"; exit 1;; esac

# ── find Steam ──────────────────────────────────────────────────────────────
STEAM=""
for s in "$HOME/.steam/root" "$HOME/.steam/steam" "$HOME/.local/share/Steam" \
         "$HOME/.steam/debian-installation" \
         "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam"; do
  [ -d "$s/steamapps" ] && { STEAM="$(cd "$s" && pwd -P)"; break; }
done
[ -n "$STEAM" ] || { echo "Steam not found (looked in ~/.steam, ~/.local/share/Steam, flatpak)"; exit 1; }
# every library folder (libraryfolders.vdf "path" entries) + the main one
LIBS=("$STEAM")
if [ -f "$STEAM/steamapps/libraryfolders.vdf" ]; then
  while IFS= read -r p; do [ -d "$p/steamapps" ] && LIBS+=("$p"); done < <(
    sed -n 's/^[[:space:]]*"path"[[:space:]]*"\(.*\)"/\1/p' "$STEAM/steamapps/libraryfolders.vdf" | sed 's#\\\\#/#g')
fi
ROOTS=("$STEAM/compatibilitytools.d" "$HOME/.steam/root/compatibilitytools.d")
for l in "${LIBS[@]}"; do ROOTS+=("$l/steamapps/common"); done

_find() { local r; for r in "${ROOTS[@]}"; do [ -x "$r/$1/proton" ] && { echo "$r/$1/proton"; return; }; done; return 1; }
PROTON=""
if [ -n "${TANARUS_PROTON:-}" ]; then
  PROTON="$(_find "$TANARUS_PROTON")" || { echo "no runtime named '$TANARUS_PROTON'. Installed:"; for r in "${ROOTS[@]}"; do for d in "$r"/*/; do [ -x "${d%/}/proton" ] && echo "   $(basename "$d")"; done; done 2>/dev/null; exit 1; }
else
  # newest GE-Proton first (built for the host, no container needed), then Valve's
  for r in "${ROOTS[@]}"; do
    for d in $(ls -d "$r"/GE-Proton*/ 2>/dev/null | sort -V -r); do [ -x "${d%/}/proton" ] && PROTON="${d%/}/proton" && break 2; done
  done
  [ -n "$PROTON" ] || PROTON="$(_find "Proton - Experimental")" || PROTON="$(_find "Proton 9.0 (Beta)")" || PROTON="$(_find "Proton 9.0")" || true
  [ -n "$PROTON" ] || { echo "no Proton found — install Proton Experimental in Steam (Library → Tools) or drop a GE-Proton into $STEAM/compatibilitytools.d"; exit 1; }
fi
RTNAME="$(basename "$(dirname "$PROTON")")"
echo "[tanarus] runtime: $RTNAME"

# Valve's own builds are meant to run inside the Steam Linux Runtime container (Steam installs
# it alongside them). GE builds run on the host directly. One prefix per runtime.
WRAP=""
case "$PROTON" in */steamapps/common/*)
  for c in SteamLinuxRuntime_4 SteamLinuxRuntime_sniper; do
    for l in "${LIBS[@]}"; do
      [ -x "$l/steamapps/common/$c/_v2-entry-point" ] && { WRAP="$l/steamapps/common/$c/_v2-entry-point --verb=run --"; break 2; }
    done
  done
  [ -n "$WRAP" ] && echo "[tanarus] inside $(basename "$(dirname "${WRAP%% *}")")" \
                 || echo "[tanarus] note: no Steam Linux Runtime container found; trying to run $RTNAME directly"
  ;;
esac
PFX="${TANARUS_PFX:-$HOME/.local/share/zimarus-pfx-$(echo "$RTNAME" | tr -cd '[:alnum:]._-')}"
mkdir -p "$PFX"

DESKTOP=""
[ -n "${TANARUS_WINDOWED:-}" ] && DESKTOP="explorer /desktop=Tanarus,1280x960"

# ── the launcher (v26.8.19 and later) ───────────────────────────────────────
# ZimarusLauncher.exe is a .NET WinForms app and it RUNS UNDER PROTON — wine-mono ships with
# GE-Proton, and on 2026-08-19 (GE-Proton10-4) it installed a release, wrote ip.dat, downloaded
# the rotation maps it was missing and started the game. Going through it here is what finally
# gives Linux the automatic updates it has never had; without it a new version only arrives when
# you download the zip by hand.
#
# It starts the game itself, passing "online". That costs you nothing: tangame.exe stores
# (arg == "offline") in a single global and reads it in exactly one place, and both branches land
# on the same instruction — the offline path only skips six NOPs. TRAINING is on the title screen
# either way, and it never touches the network.
#
# Two things it cannot do under Wine. Both are harmless, and the second one is why your setup is
# safe:
#   * the desktop / Start-menu shortcut — Wine has no WScript.Shell CreateShortcut, so it writes
#     "Could not create launcher shortcuts" to ZimarusLauncher.log and carries on;
#   * and because that step fails, it never reaches its legacy-file cleanup — so _Start.bat,
#     Tanarus_Start.bat, update.ps1 and this script are all left exactly where they are.
#
# Skipped for a development tree (a `skipupdate` file beside the game, the same opt-out the
# Windows updater has always honoured) or with TANARUS_NO_UPDATE=1.
LAUNCH="$GAME_DIR/tangame.exe"; LAUNCH_ARG="$MODE"
if [ -f "$GAME_DIR/ZimarusLauncher.exe" ] && [ ! -f "$GAME_DIR/skipupdate" ] && [ -z "${TANARUS_NO_UPDATE:-}" ]; then
  LAUNCH="$GAME_DIR/ZimarusLauncher.exe"; LAUNCH_ARG=""
  echo "[tanarus] starting through ZimarusLauncher.exe — updates + missing maps (TANARUS_NO_UPDATE=1 to skip)"
fi

echo "[tanarus] server: $(tr -d '\r' < "$GAME_DIR/ip.dat" 2>/dev/null)   mode: $MODE"
cd "$GAME_DIR"
exec env STEAM_COMPAT_CLIENT_INSTALL_PATH="$STEAM" STEAM_COMPAT_DATA_PATH="$PFX" SteamGameId=42 \
  $WRAP "$PROTON" run $DESKTOP "$LAUNCH" $LAUNCH_ARG
