#!/bin/bash
# stargate-redial - startet "Stargate SG-1 The Alliance: Redial" unter Proton (umu-launcher)
# oder Wine. Das Spiel liegt schreibgeschützt in /opt/stargate-redial/game; beim ersten Start
# entsteht unter ~/.local/share/stargate-redial eine eigene, beschreibbare Ansicht davon.
#
# Copyright (c) 2026 Gate Wanderers - MIT-Lizenz
set -euo pipefail
shopt -s nullglob

PROG=${0##*/}
# <Redial-Version>-<Paketstand> (= pkgver-pkgrel; tools/release.py prüft das)
VERSION=0.1.7-2
HERE=$(dirname -- "$(realpath -- "$0")")
BASE=${STARGATE_REDIAL_BASE:-/opt/stargate-redial/game}
DATA=${STARGATE_REDIAL_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}/stargate-redial}
GAME=$DATA/game
STATE=$DATA/state
EPIC_TOS_URL=https://legal.epicgames.com/en-US/epicgames/tos
# entstehen beim Spielen und gehören dem Spieler; nie aus der Vorlage übernehmen
RUNTIME_FILES='*.log|Running.ini|PlayerProfile.ini|SGASaves.ini|Stats.ini|SGSpeech.ini|UPlaylists.ini|UnrealEd.ini|CacheRecords.ucl|D3DShaderCache.dat'
# Abschnitte der Haupt-ini, die bei einem Update aus der Spielerdatei erhalten bleiben
# Vollbild-Auflösung der Vorlage und die Abschnitte, in denen sie steht
DEFAULT_RES=1280x720
RES_SECTIONS='WinDrv.WindowsClient SDLDrv.SDLClient'
KEEP_SECTIONS='WinDrv.WindowsClient|SDLDrv.SDLClient|D3D11Drv.D3D11RenderDevice|D3D9Drv.D3D9RenderDevice|D3DDrv.D3DRenderDevice|OpenGLDrv.OpenGLRenderDevice|ALAudio.ALAudioSubsystem|IpDrv.MasterServerLink|Engine.Player'

msg() { printf '%s: %s\n' "$PROG" "$*" >&2; }
die() { printf '%s: Fehler: %s\n' "$PROG" "$*" >&2; notify "$*"; exit 1; }
notify() { [ -t 2 ] || ! command -v notify-send >/dev/null || notify-send -i stargate-redial -- "Stargate Redial" "$1" || true; }

usage() {
  cat <<EOF
Aufruf: $PROG [Optionen] [-- Spielargumente]

  --wine             mit Wine statt Proton starten (auch: STARGATE_REDIAL_RUNNER=wine)
  --proton           mit Proton über umu-run starten (Standard)
  --lang de|en       Sprache umstellen (de = inoffizielle Übersetzung von Gate Wanderers)
  --sprache de|en    dasselbe wie --lang
  --windowed         im Fenster starten (schreibt StartupFullscreen=False)
  --aufloesung BxH|auto
                     Vollbild-Auflösung setzen, z. B. 2560x1440 (640..7680 x 480..4320);
                     auto liest sie neu vom Hauptbildschirm
  --resolution BxH|auto
                     dasselbe wie --aufloesung
  --mangohud         MangoHud einblenden
  --no-gamemode      GameMode nicht benutzen, auch wenn er installiert ist
  --setup-only       nur den Spielerordner einrichten bzw. abgleichen, nicht starten
  --reset-config     Einstellungen auf die Vorlage zurücksetzen (alte Dateien werden gesichert)
  --accept-tos       Epic-Games-Nutzungsbedingungen ohne Rückfrage annehmen
  --check-updates    jetzt nach einer neuen Version suchen und das Ergebnis zeigen (ohne Start)
  --update-check on|off
                     die tägliche Suche nach Updates beim Start ein- oder ausschalten (bleibt so)
  --no-update-check  bei diesem Start nicht nach Updates suchen
  --version | --help

Update-Hinweis: Beim Start lädt das Programm höchstens einmal am Tag die signierte Liste
https://gatewanderers.de/downloads/stargate-redial/update.json (Frist 6 Sekunden, ohne
Verbindung geht es still weiter) und meldet eine neue Version. Aktualisiert wird das Paket mit
pacman bzw. deinem AUR-Helfer (paru, yay), nicht vom Programm selbst. Gesendet wird nur die
Anfrage mit "User-Agent: stargate-redial-updater/$VERSION", keine Kennung.

Auflösung: Beim ersten Start liest das Programm die Auflösung des Hauptbildschirms
(kscreen-doctor, wlr-randr oder xrandr) und trägt sie ein, solange noch Redials Vorgabe
$DEFAULT_RES drinsteht. Eine im Spiel gewählte Auflösung bleibt; --reset-config erkennt neu.

Umgebung: STARGATE_REDIAL_RUNNER (proton|wine), STARGATE_REDIAL_GAMEID (umu-default),
  PROTONPATH (Standard: GE-Proton, lädt umu beim ersten Start), STARGATE_REDIAL_HOME,
  STARGATE_REDIAL_BASE, WINE (Pfad zum wine-Programm), STARGATE_REDIAL_UPDATE_CHECK=0.
Spielerdaten: $DATA
EOF
}

valid_res() { # BxH in 640..7680 x 480..4320, nur Ziffern ohne führende Null
  [[ $1 =~ ^([1-9][0-9]{2,3})x([1-9][0-9]{2,3})$ ]] || return 1
  ((BASH_REMATCH[1] >= 640 && BASH_REMATCH[1] <= 7680 && BASH_REMATCH[2] >= 480 && BASH_REMATCH[2] <= 4320))
}
res_opt() {
  [ "$1" = auto ] || valid_res "$1" || die "--aufloesung/--resolution: BxH (640..7680 x 480..4320, z. B. 2560x1440) oder auto"
  RES_SET=$1
}

RUNNER=${STARGATE_REDIAL_RUNNER:-proton} LANG_SET='' WINDOWED=0 MANGO=${STARGATE_REDIAL_MANGOHUD:-0}
GAMEMODE=${STARGATE_REDIAL_GAMEMODE:-1} SETUP_ONLY=0 RESET=0 ACCEPT=${STARGATE_REDIAL_ACCEPT_TOS:-0}
UPDATE_CHECK=${STARGATE_REDIAL_UPDATE_CHECK:-1} CHECK_NOW=0 SET_CHECK='' RES_SET=''
GAME_ARGS=()
while [ $# -gt 0 ]; do
  case $1 in
    --wine) RUNNER=wine ;;
    --proton | --umu) RUNNER=proton ;;
    --lang | --sprache) [ $# -ge 2 ] || die "$1 braucht de oder en"; LANG_SET=$2; shift ;;
    --lang=* | --sprache=*) LANG_SET=${1#*=} ;;
    --windowed) WINDOWED=1 ;;
    --aufloesung | --resolution) [ $# -ge 2 ] || die "$1 braucht BxH oder auto"; res_opt "$2"; shift ;;
    --aufloesung=* | --resolution=*) res_opt "${1#*=}" ;;
    --mangohud) MANGO=1 ;;
    --no-gamemode) GAMEMODE=0 ;;
    --setup-only) SETUP_ONLY=1 ;;
    --reset-config) RESET=1 ;;
    --accept-tos) ACCEPT=1 ;;
    --check-updates) CHECK_NOW=1 ;;
    --update-check) [ $# -ge 2 ] || die "--update-check braucht on oder off"; SET_CHECK=$2; shift ;;
    --update-check=*) SET_CHECK=${1#*=} ;;
    --no-update-check) UPDATE_CHECK=0 ;;
    --version) printf '%s %s\n' "$PROG" "$VERSION"; exit 0 ;;
    -h | --help) usage; exit 0 ;;
    --) shift; GAME_ARGS=("$@"); break ;;
    *) die "unbekannte Option: $1 (siehe --help)" ;;
  esac
  shift
done
case $RUNNER in proton | umu) RUNNER=proton ;; wine) ;; *) die "STARGATE_REDIAL_RUNNER: proton oder wine" ;; esac
case $LANG_SET in '' | de | en) ;; *) die "--lang/--sprache: de oder en" ;; esac
case $SET_CHECK in '' | on | off) ;; *) die "--update-check: on oder off" ;; esac

# --- Update-Hinweis ---------------------------------------------------------------------
# Kein Selbst-Update: das Paket gehört pacman. stargate-redial-update prüft die signierte Liste
# (minisign, fester Schlüssel) höchstens einmal am Tag und sagt nur, ob es Neues gibt. Auch der
# Weg ohne Paket ("Andere Linux-Distributionen" im README) ist keine Installation, sondern läuft
# aus dem entpackten Skript-Archiv; er wird von Hand aktualisiert.
updater() {
  local f
  for f in "$HERE/stargate-redial-update" /usr/lib/stargate-redial/stargate-redial-update; do
    [ -f "$f" ] && { printf '%s\n' "$f"; return 0; }
  done
  return 1
}
update_hint() { # Version, Redial-Version
  local how
  if [ "$HERE" = /usr/bin ]; then
    how="Aktualisieren mit pacman bzw. deinem AUR-Helfer (z. B. paru -Syu oder yay -Syu), oder stargate-redial-aur-$1.tar.gz von https://gatewanderers.de/redial/ entpacken und darin makepkg -si"
  else
    how="neue Skripte (stargate-redial-$1.tar) von https://gatewanderers.de/redial/ holen und die Schritte ohne Paket wiederholen"
  fi
  msg "neue Version $1 verfügbar (Redial $2, installiert: $VERSION). $how"
  notify "Neue Version $1 verfügbar (Redial $2). $how"
}
check_updates() { # 1 = jetzt und mit Ergebnis
  local up out rc=0 kind a b force=()
  [ "$1" = 1 ] || [ "$UPDATE_CHECK" != 0 ] || return 0
  [ "$1" = 0 ] || force=(--force)
  if ! up=$(updater) || ! command -v python3 >/dev/null; then
    [ "$1" = 0 ] || msg "Update-Prüfung nicht möglich (python3 oder stargate-redial-update fehlt)"
    return 0
  fi
  # die Frist (6 s) hält stargate-redial-update selbst; timeout fängt alles andere ab
  local to=()
  ! command -v timeout >/dev/null || to=(timeout -k 1 8)
  out=$("${to[@]}" python3 -I "$up" check --installed "$VERSION" --state "$STATE" "${force[@]}" 9>&- 2>/dev/null) || rc=$?
  IFS=$'\t' read -r kind a b <<<"$out" || true
  case $kind in
    update) update_hint "$a" "$b" ;;
    current) [ "$1" = 0 ] || msg "aktuell (installiert: $VERSION, Liste: $a)" ;;
    *) [ "$1" = 0 ] || msg "Update-Prüfung: ${kind:-Fehler} ${a:-Code $rc}" ;;
  esac
  return 0
}
if [ -n "$SET_CHECK" ]; then
  mkdir -p "$STATE"; printf '%s\n' "$SET_CHECK" >"$STATE/update-check"
  msg "tägliche Update-Prüfung: $SET_CHECK ($STATE/update-check)"; exit 0
fi
if [ "$CHECK_NOW" = 1 ]; then mkdir -p "$STATE"; check_updates 1; exit 0; fi

[ -f "$BASE/System/UT2004.exe" ] && [ -d "$BASE/SGAlliance/System" ] ||
  die "Spiel nicht gefunden in $BASE (Paket stargate-redial installiert?)"

# --- Nutzungsbedingungen (wie bei den OldUnreal-Installern) ------------------------------
tos_text() {
  cat <<EOF
Für Nutzung und Weitergabe dieses Spiels gelten die Nutzungsbedingungen von Epic Games;
sie gehen allen anderen Lizenzbedingungen vor, die dem Spiel beiliegen.
The Epic Games Terms of Service apply to the use and distribution of this game,
and they supersede any other end user agreements that may accompany the game.

  $EPIC_TOS_URL

Die Spieldateien wurden aus deinen eigenen Downloads gebaut und sind nur für dich bestimmt:
nicht weitergeben oder hochladen (Hinweis des Redial-Projekts).
EOF
}
accept_tos() {
  [ -f "$STATE/tos-accepted" ] && return 0
  local ok=1
  if [ "$ACCEPT" = 1 ]; then ok=0
  elif [ -t 0 ] && [ -t 2 ]; then
    tos_text >&2; printf '\nStimmst du den Nutzungsbedingungen zu? / Do you agree? [j/N] ' >&2
    local a; read -r a || true; case $a in [jJyY]*) ok=0 ;; esac
  elif command -v kdialog >/dev/null; then
    kdialog --title "Terms of Service" --yesno "$(tos_text)" >/dev/null 2>&1 && ok=0
  elif command -v zenity >/dev/null; then
    tos_text | zenity --text-info --title="Terms of Service" \
      --checkbox="Ich stimme den Epic Games Terms of Service zu / I agree" \
      --width=560 --height=420 >/dev/null 2>&1 && ok=0
  else
    die "Bitte einmal im Terminal starten: $PROG (Nutzungsbedingungen bestätigen)"
  fi
  [ "$ok" -eq 0 ] || die "Nutzungsbedingungen nicht angenommen, Abbruch."
  mkdir -p "$STATE"; date -u +%FT%TZ >"$STATE/tos-accepted"
}

# --- beschreibbare Ansicht des Spielordners ----------------------------------------------
declare -A REC=()
load_rec() { local h p; [ -f "$STATE/copied.sha256" ] || return 0
  while read -r h p; do [ -n "$p" ] && REC[$p]=$h; done <"$STATE/copied.sha256"; }
save_rec() { local p; for p in "${!REC[@]}"; do printf '%s %s\n' "${REC[$p]}" "$p"; done |
  sort -k2 >"$STATE/copied.sha256.new"; mv -f "$STATE/copied.sha256.new" "$STATE/copied.sha256"; }
sha() { sha256sum -- "$1" | cut -d' ' -f1; }

# Abschnitte $KEEP_SECTIONS aus der alten Spielerdatei ($2) in die neue Vorlage ($1) übernehmen
merge_ini() {
  awk -v keep="$KEEP_SECTIONS" '
    BEGIN { n = split(keep, a, "|"); for (i = 1; i <= n; i++) K[a[i]] = 1 }
    function sec(l) { s = l; sub(/^\[/, "", s); sub(/\][ \t\r]*$/, "", s); return s }
    FNR == 1 { file++; cur = "" }
    /^\[.*\][ \t\r]*$/ { cur = sec($0) }
    file == 1 { if (cur in K) { have[cur] = 1; old[cur] = old[cur] $0 "\n" } next }
    /^\[.*\][ \t\r]*$/ { skip = (cur in have); if (skip) { printf "%s", old[cur]; done[cur] = 1; next } }
    !skip { print }
    END { for (c in have) if (!(c in done)) printf "%s", old[c] }
  ' "$2" "$1"
}

# eine ini/ucl-Datei aus der Vorlage holen, ohne Änderungen des Spielers zu überschreiben
sync_copy() {
  local src=$1 dst=$2 rel=$3 new cur old
  new=$(sha "$src")
  if [ ! -e "$dst" ] || [ -L "$dst" ]; then
    rm -f -- "$dst"; cp -- "$src" "$dst"; chmod u+w -- "$dst"; REC[$rel]=$new; return
  fi
  cur=$(sha "$dst"); old=${REC[$rel]-}
  [ "$cur" != "$new" ] || { REC[$rel]=$new; return; }
  if [ "$cur" = "$old" ]; then # vom Spiel nie verändert: neue Fassung übernehmen
    cp -- "$src" "$dst"; chmod u+w -- "$dst"; REC[$rel]=$new
  elif [ "$old" != "$new" ] && [ "$rel" = SGAlliance/System/SGAlliance.ini ]; then
    cp -- "$dst" "$dst.vor-update"
    merge_ini "$src" "$dst.vor-update" >"$dst"; REC[$rel]=$new
    msg "SGAlliance.ini auf neue Vorlage gebracht, Grafik/Ton übernommen (alt: $rel.vor-update)"
  elif [ "$old" != "$new" ]; then
    msg "behalte deine geänderte $rel (Vorlage neu: $src)"
  fi
}

in_list() { # Name, durch | getrennte Muster
  local p pats
  IFS='|' read -ra pats <<<"$2"
  # shellcheck disable=SC2053
  for p in "${pats[@]}"; do [[ $1 == $p ]] && return 0; done
  return 1
}

farm_dir() { # Vorlagenordner, Zielordner, relativer Pfad
  local src=$1 dst=$2 rel=$3 f n
  mkdir -p -- "$dst"
  for f in "$src"/*; do
    n=${f##*/}
    ! in_list "$n" "$RUNTIME_FILES" || continue
    if [ -d "$f" ]; then ln -sfn -- "$f" "$dst/$n"
    elif [[ $n == *.ini || $n == *.ucl ]]; then sync_copy "$f" "$dst/$n" "$rel/$n"
    elif [ -L "$dst/$n" ] || [ ! -e "$dst/$n" ]; then ln -sfn -- "$f" "$dst/$n"
    fi
  done
}

link_dir() { # alle Einträge außer den genannten als Symlink
  local src=$1 dst=$2 skip=$3 f n
  mkdir -p -- "$dst"
  for f in "$src"/*; do
    n=${f##*/}
    ! in_list "$n" "$skip" || continue
    if [ -L "$dst/$n" ] || [ ! -e "$dst/$n" ]; then ln -sfn -- "$f" "$dst/$n"; fi
  done
}

sync_game() {
  local stamp d
  stamp=$(cat "$BASE/.stargate-redial-build" 2>/dev/null || echo "ohne-stempel")
  stamp+=" base=$BASE"
  if [ "$RESET" -eq 0 ] && [ -d "$GAME/System" ] && [ "$(cat "$STATE/stamp" 2>/dev/null)" = "$stamp" ]; then
    return 0
  fi
  msg "richte Spielerordner ein: $GAME"
  mkdir -p "$GAME" "$STATE"
  if [ "$RESET" -eq 1 ] && [ -d "$GAME/System" ]; then
    d=$DATA/sicherung-$(date +%Y%m%d-%H%M%S)
    mkdir -p "$d/System" "$d/SGAlliance/System"
    cp -a "$GAME"/System/*.ini "$d/System/" 2>/dev/null || true
    cp -a "$GAME"/SGAlliance/System/*.ini "$d/SGAlliance/System/" 2>/dev/null || true
    # ohne Merkdatei wird die Auflösung danach neu erkannt
    rm -f "$GAME"/System/*.ini "$GAME"/System/*.ucl "$GAME"/SGAlliance/System/*.ini "$STATE/copied.sha256" "$STATE/resolution"
    msg "alte Einstellungen gesichert in $d"
  fi
  load_rec
  # verwaiste Links aus einer früheren Version entfernen
  find "$GAME" -maxdepth 3 -xtype l -delete 2>/dev/null || true
  link_dir "$BASE" "$GAME" 'System|SGAlliance|SystemARM64|SystemPPC64LE|Installer|.stargate-redial-build'
  link_dir "$BASE/SGAlliance" "$GAME/SGAlliance" 'System|Saves|Server|Launcher'
  farm_dir "$BASE/System" "$GAME/System" System
  farm_dir "$BASE/SGAlliance/System" "$GAME/SGAlliance/System" SGAlliance/System
  for d in Save Saves Cache ScreenShots Demos UserLogs SGAlliance/Saves; do
    [ -L "$GAME/$d" ] && rm -f -- "$GAME/$d"
    mkdir -p -- "$GAME/$d"
  done
  save_rec
  printf '%s\n' "$stamp" >"$STATE/stamp"
}

# [Engine.Engine] Language= umstellen; die zweite Language=-Zeile ([Editor.EditorEngine]) bleibt
set_ini_key() { # Datei Abschnitt Schlüssel Wert
  local f=$1 tmp
  [ -f "$f" ] || return 0
  tmp=$(mktemp "$f.XXXXXX")
  awk -v sec="[$2]" -v key="$3" -v val="$4" '
    { line = $0; cr = sub(/\r$/, "", line) ? "\r" : "" }
    /^\[/ { if (insec && !done) { print key "=" val cr; done = 1 } insec = (line == sec) }
    insec && !done && index(line, key "=") == 1 { print key "=" val cr; done = 1; next }
    { print }
    END { if (insec && !done) print key "=" val }
  ' "$f" >"$tmp" && mv -f -- "$tmp" "$f"
}

# --- Vollbild-Auflösung -------------------------------------------------------------------
# Auflösung des Hauptbildschirms in echten Pixeln (Skalierung egal), Ausgabe "BxH Werkzeug".
# Der Reihe nach: KDE (kscreen-doctor, Hauptbildschirm = kleinste priority), wlroots (wlr-randr,
# erster eingeschalteter Ausgang, bevorzugt der bei 0,0), X11/XWayland (xrandr, "primary").
# Jedes Werkzeug hat 3 Sekunden; klappt nichts, bleibt es still bei der Vorgabe.
screen_size() {
  [ -n "${WAYLAND_DISPLAY:-}${DISPLAY:-}" ] && command -v python3 >/dev/null || return 1
  local t out py to=() a=()
  ! command -v timeout >/dev/null || to=(timeout -k 1 3)
  py=$(cat <<'EOF'
import json, re, sys
tool, raw = sys.argv[1], sys.stdin.read(4 << 20)
def num(v):
    return v if isinstance(v, int) and not isinstance(v, bool) else None
def size(w, h, swap):
    return None if num(w) is None or num(h) is None else (h, w) if swap else (w, h)
def kscreen(d):
    best = None
    for o in d.get("outputs") or []:
        if not isinstance(o, dict) or o.get("connected") is not True or o.get("enabled") is not True:
            continue
        p = num(o.get("priority"))
        if p is None or p < 1:  # ältere Plasma-Versionen: "primary": true
            p = 0 if o.get("primary") is True else 1 << 30
        for m in o.get("modes") or []:
            if isinstance(m, dict) and str(m.get("id")) == str(o.get("currentModeId")):
                sz = m.get("size") or {}
                r = size(sz.get("width"), sz.get("height"), o.get("rotation") in (2, 8))
                if r and (best is None or p < best[0]):
                    best = (p, r)
    return best and best[1]
def wlr(d):
    found = []
    for o in d if isinstance(d, list) else []:
        if not isinstance(o, dict) or o.get("enabled") is not True:
            continue
        pos = o.get("position") or {}
        swap = str(o.get("transform", "normal")) in ("90", "270", "flipped-90", "flipped-270")
        for m in o.get("modes") or []:
            if isinstance(m, dict) and m.get("current") is True:
                r = size(m.get("width"), m.get("height"), swap)
                if r:
                    found.append((0 if pos.get("x") == 0 and pos.get("y") == 0 else 1, len(found), r))
    return min(found)[2] if found else None
def xrandr(text):
    best = None
    for line in text.splitlines():
        m = re.match(r"(\S+) connected (primary )?([0-9]+)x([0-9]+)\+-?[0-9]+\+-?[0-9]+", line)
        if m and (best is None or (m.group(2) and not best[0])):
            best = (bool(m.group(2)), (int(m.group(3)), int(m.group(4))))
    return best and best[1]
parse = {"kscreen-doctor": lambda: kscreen(json.loads(raw[raw.index("{"):])), "wlr-randr": lambda: wlr(json.loads(raw))}
try:
    r = parse.get(tool, lambda: xrandr(raw))()
except (ValueError, AttributeError, TypeError):
    r = None
print(f"{r[0]}x{r[1]}") if r else sys.exit(1)
EOF
)
  for t in kscreen-doctor wlr-randr xrandr; do
    command -v "$t" >/dev/null || continue
    case $t in kscreen-doctor) a=(-j) ;; wlr-randr) a=(--json) ;; xrandr) a=(--query) ;; esac
    out=$("${to[@]}" "$t" "${a[@]}" </dev/null 2>/dev/null 9>&- | python3 -I -c "$py" "$t" 2>/dev/null 9>&-) || continue
    if valid_res "$out"; then printf '%s %s\n' "$out" "$t"; return 0; fi
  done
  return 1
}

ini_res() { # Datei -> je vorhandenem Abschnitt aus $RES_SECTIONS eine Zeile "BxH" (fehlt etwas: "?")
  awk -v secs="$RES_SECTIONS" '
    BEGIN { n = split(secs, a, " "); for (i = 1; i <= n; i++) S["[" a[i] "]"] = 1 }
    function out() { if (cur) print ((x == "" || y == "") ? "?" : x "x" y) }
    { sub(/\r$/, "") }
    /^\[/ { out(); cur = ($0 in S); x = y = ""; next }
    cur && x == "" && index($0, "FullscreenViewportX=") == 1 { x = substr($0, 21); sub(/[ \t]+$/, "", x) }
    cur && y == "" && index($0, "FullscreenViewportY=") == 1 { y = substr($0, 21); sub(/[ \t]+$/, "", y) }
    END { out() }' "$1"
}

# Nur von selbst, solange die Vorlage drinsteht und die Merkdatei fehlt; mit --aufloesung immer.
apply_resolution() {
  local ini=$1 mark=$STATE/resolution res src v s vals=()
  [ -f "$ini" ] || return 0
  mapfile -t vals < <(ini_res "$ini")
  if [ "${#vals[@]}" -eq 0 ]; then
    [ -z "$RES_SET" ] || msg "Warnung: keine Vollbild-Auflösung in $ini (${RES_SECTIONS// /, })"
    return 0
  fi
  if [ -z "$RES_SET" ]; then
    [ ! -e "$mark" ] || return 0
    for v in "${vals[@]}"; do
      # vom Spieler (im Spiel) gewählt: nie wieder von selbst anfassen
      [ "$v" = "$DEFAULT_RES" ] || { printf 'user %s %s\n' "$v" "$(date -u +%FT%TZ)" >"$mark"; return 0; }
    done
  fi
  if [ -z "$RES_SET" ] || [ "$RES_SET" = auto ]; then
    if ! read -r res src < <(screen_size); then
      [ -z "$RES_SET" ] || msg "Auflösung des Hauptbildschirms nicht erkannt, bleibt bei ${vals[0]} (z. B. --aufloesung 1920x1080)"
      return 0
    fi
  else
    res=$RES_SET src=Option
  fi
  for s in $RES_SECTIONS; do
    set_ini_key "$ini" "$s" FullscreenViewportX "${res%x*}"
    set_ini_key "$ini" "$s" FullscreenViewportY "${res#*x}"
  done
  printf '%s %s %s\n' "$res" "$src" "$(date -u +%FT%TZ)" >"$mark"
  msg "Vollbild-Auflösung: $res ($src)"
}

apply_settings() {
  local ini=$GAME/SGAlliance/System/SGAlliance.ini code
  [ -z "$LANG_SET" ] || printf '%s\n' "$LANG_SET" >"$STATE/language"
  case $(cat "$STATE/language" 2>/dev/null) in
    de) code=det
      [ -n "$(echo "$BASE"/SGAlliance/System/*.det)" ] ||
        msg "Warnung: keine deutschen Sprachdateien im Spielordner" ;;
    en) code=int ;;
    *) code='' ;;
  esac
  if [ -n "$code" ] && ! awk -v c="Language=$code" '/^\[Engine\.Engine\]/{s=1;next} /^\[/{s=0}
       s && /^Language=/{sub(/\r$/,""); r=($0==c)?0:1; f=1; exit} END{exit f?r:1}' "$ini"; then
    set_ini_key "$ini" Engine.Engine Language "$code"
  fi
  [ "$WINDOWED" -eq 0 ] || set_ini_key "$ini" WinDrv.WindowsClient StartupFullscreen False
  apply_resolution "$ini"
}

# --- Start ------------------------------------------------------------------------------
launch() {
  local cmd=() exe=$GAME/System/UT2004.exe
  if [ "$RUNNER" = proton ]; then
    command -v umu-run >/dev/null || die "umu-run fehlt (Paket umu-launcher) - oder mit --wine starten"
    export WINEPREFIX=$DATA/prefix-proton
    export GAMEID=${STARGATE_REDIAL_GAMEID:-umu-default}
    export PROTONPATH=${PROTONPATH:-GE-Proton}
    [ -d "$WINEPREFIX" ] || msg "erster Start mit Proton: umu lädt Proton und die Steam-Laufzeit (Internet nötig)"
    cmd=(umu-run "$exe")
  else
    local wine=${WINE:-wine}
    command -v "$wine" >/dev/null || die "wine fehlt (Paket wine oder wine-cachyos) - oder ohne --wine starten"
    export WINEPREFIX=$DATA/prefix-wine
    export WINEDLLOVERRIDES=${WINEDLLOVERRIDES:-mscoree=d;mshtml=d;winemenubuilder.exe=d}
    export WINEDEBUG=${WINEDEBUG:--all}
    cmd=("$wine" "$exe")
  fi
  mkdir -p -- "$WINEPREFIX"
  if [ "$MANGO" = 1 ]; then
    export MANGOHUD=1
    [ "$RUNNER" = proton ] || ! command -v mangohud >/dev/null || cmd=(mangohud "${cmd[@]}")
  fi
  [ "$GAMEMODE" = 0 ] || ! command -v gamemoderun >/dev/null || cmd=(gamemoderun "${cmd[@]}")
  cmd+=(-mod=SGAlliance -nohomedir "${GAME_ARGS[@]}")
  cd -- "$GAME/System"
  msg "starte: ${cmd[*]}"
  # Sperre nicht an Wine/Proton vererben, sonst hielte der wineserver sie fest
  "${cmd[@]}" 9>&-
}

mkdir -p "$DATA" "$STATE"
exec 9>"$STATE/lock"
flock -n 9 || die "Stargate Redial läuft schon (Sperre $STATE/lock)"
accept_tos
sync_game
apply_settings
# Absturzmarke eines früheren Laufs; sonst fragt UT2004 nach dem abgesicherten Modus
rm -f -- "$GAME/System/Running.ini"
[ "$SETUP_ONLY" -eq 0 ] || { msg "Spielerordner bereit: $GAME"; exit 0; }
check_updates 0
launch
