#!/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.9-1
HERE=$(dirname -- "$(realpath -- "$0")")
# vom grafischen Installer eingerichtet (Marker .gw-installed): das Spiel liegt neben dem
# Skriptordner (<Installationsordner>/game); unter /usr/bin gibt es den Marker nie
if [ -z "${STARGATE_REDIAL_BASE:-}" ] && [ -e "$HERE/.gw-installed" ] && [ -f "$HERE/../game/.stargate-redial-build" ]; then
  BASE=$(realpath -- "$HERE/../game")
else
  BASE=${STARGATE_REDIAL_BASE:-/opt/stargate-redial/game}
fi
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'
# (dazu die im Spiel gewählte Sprache [SGShim.SGL10n]; Language= aus [Engine.Engine] übernimmt sync_copy)
KEEP_SECTIONS='WinDrv.WindowsClient|SDLDrv.SDLClient|D3D11Drv.D3D11RenderDevice|D3D9Drv.D3D9RenderDevice|D3DDrv.D3DRenderDevice|OpenGLDrv.OpenGLRenderDevice|ALAudio.ALAudioSubsystem|IpDrv.MasterServerLink|Engine.Player|SGShim.SGL10n'
# Dateien im Spielerordner, in denen das Spiel die Sprachwahl (Options -> Language) ablegen kann
LANG_INIS='SGAlliance/System/SGAllianceUser.ini SGAlliance/System/SGAlliance.ini'

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)
  --sprache de|en|fr Sprache umstellen (Deutsch: Übersetzung von Gate Wanderers, bei Redial
                     dabei; geht auch im Spiel unter Options -> Language)
  --lang de|en|fr    dasselbe wie --sprache
  --texturen original|2k|4k
                     HD-Texturen von Redial: 2k lädt etwa 1,2 GB (3 GB auf der Platte, dazu 1 GB
                     Kopie der Originale), 4k weitere 1,6 GB (5,8 GB). original stellt die von
                     2005 wieder her und lädt nichts. Geht auch im Spiel unter Options -> Video
                     -> HD Textures (beim nächsten Start). Nochmal 2k bzw. 4k holt neue Fassungen.
  --textures ...     dasselbe wie --texturen
  --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; eine Installation über
den grafischen Installer aktualisiert dieser. Gesendet wird nur die Anfrage mit
"User-Agent: stargate-redial-updater/$VERSION", keine Kennung.

HD-Texturen: Sie kommen vom Redial-Projekt (github.com/Stargate-Redial/alliance-redial-hd);
geladen und geprüft werden sie von Redials eigenem Werkzeug. Ohne --texturen und ohne Wahl im
Spiel wird nichts geladen.

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=''
TEX_SET=''
tex_opt() {
  TEX_SET=${1,,}
  case $TEX_SET in original | 2k | 4k) ;; *) die "--texturen/--textures: original, 2k oder 4k" ;; esac
}
GAME_ARGS=()
while [ $# -gt 0 ]; do
  case $1 in
    --wine) RUNNER=wine ;;
    --proton | --umu) RUNNER=proton ;;
    --lang | --sprache) [ $# -ge 2 ] || die "$1 braucht de, en oder fr"; LANG_SET=$2; shift ;;
    --lang=* | --sprache=*) LANG_SET=${1#*=} ;;
    --texturen | --textures) [ $# -ge 2 ] || die "$1 braucht original, 2k oder 4k"; tex_opt "$2"; shift ;;
    --texturen=* | --textures=*) tex_opt "${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 | fr) ;; *) die "--lang/--sprache: de, en oder fr" ;; 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. Der Weg
# ohne Paket aktualisiert sich über den grafischen Installer (stargate-redial-installer) oder,
# bei den drei Befehlen aus dem README, von Hand.
helper() { # Name eines Programms neben dem Starter oder aus dem Paket
  local f
  for f in "$HERE/$1" "/usr/lib/stargate-redial/$1"; do
    [ -f "$f" ] && { printf '%s\n' "$f"; return 0; }
  done
  return 1
}
updater() { helper stargate-redial-update; }
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"
  elif [ -e "$HERE/.gw-installed" ]; then
    how="im Startmenü den Eintrag Stargate Redial Installer öffnen und dort Aktualisieren wählen (oder $HERE/stargate-redial-installer)"
  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.
# Dazu Paths= in [Core.System], die nur die alte Datei hat (ergänzt vom Spieler oder einem Zusatz
# wie HD-Texturen: Paths=../SGAlliance/HDTextures/*.utx). Sie kommen an dieselbe Stelle, vor die
# nächste alte Zeile, die auch die Vorlage hat: die Reihenfolge entscheidet, welches Paket gilt.
merge_ini() {
  awk -v keep="$KEEP_SECTIONS" '
    BEGIN { n = split(keep, a, "|"); for (i = 1; i <= n; i++) K[a[i]] = 1; EOS = SUBSEP "ende" }
    function sec(l) { s = l; sub(/^\[/, "", s); sub(/\][ \t\r]*$/, "", s); return s }
    function norm(l) { sub(/[ \t\r]+$/, "", l); return tolower(l) }
    function flush_core(   i, j, k, m, inew, ins) {
      for (i = 1; i <= nn; i++) inew[norm(nc[i])] = 1
      for (i = 1; i <= on; i++) {
        k = norm(oc[i])
        if (k in inew || k !~ /^paths=/) continue
        for (j = i + 1; j <= on && (norm(oc[j]) == "" || !(norm(oc[j]) in inew)); j++) ;
        k = (j <= on) ? norm(oc[j]) : EOS
        ins[k] = ins[k] oc[i] "\n"
      }
      for (m = nn; m > 0 && norm(nc[m]) == ""; m--) ;
      for (i = 1; i <= nn; i++) {
        if (i == m + 1 && (EOS in ins)) { printf "%s", ins[EOS]; delete ins[EOS] }
        k = norm(nc[i]); if (k in ins) { printf "%s", ins[k]; delete ins[k] }
        print nc[i]
      }
      if (EOS in ins) printf "%s", ins[EOS]
      nn = 0
    }
    FNR == 1 { file++; cur = "" }
    /^\[.*\][ \t\r]*$/ { if (file == 2 && cur == "Core.System") flush_core(); cur = sec($0) }
    file == 1 {
      if (cur in K) { have[cur] = 1; old[cur] = old[cur] $0 "\n" }
      if (cur == "Core.System" && !/^\[/) oc[++on] = $0
      next
    }
    /^\[.*\][ \t\r]*$/ { skip = (cur in have); if (skip) { printf "%s", old[cur]; done[cur] = 1; next } }
    !skip && cur == "Core.System" && !/^\[/ { nc[++nn] = $0; next }
    !skip { print }
    END { if (file == 2 && cur == "Core.System") flush_core(); 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"
    # die Grafikoptionen von Redial nur, wenn die neue Fassung denselben Aufbau hat (wie Redial
    # selbst, das bei einer neuen SettingsVersion Werte ersetzt)
    local keep=$KEEP_SECTIONS sv
    sv=$(ini_get "$src" SGGUI.SGGfxOptions SettingsVersion)
    [ -z "$sv" ] || [ "$sv" != "$(ini_get "$dst" SGGUI.SGGfxOptions SettingsVersion)" ] || keep+='|SGGUI.SGGfxOptions'
    KEEP_SECTIONS=$keep merge_ini "$src" "$dst.vor-update" >"$dst"; REC[$rel]=$new
    # 0.1.9: 128 statt 32 Tonkanäle, einmalig und nur, wo noch die alte Vorgabe steht (wie Redial)
    if [ "$(ini_get "$dst" ALAudio.ALAudioSubsystem Channels)" = 32 ] && [ ! -e "$STATE/channels-128" ] &&
      [ "$(ini_get "$src" ALAudio.ALAudioSubsystem Channels)" = 128 ]; then
      set_ini_key "$dst" ALAudio.ALAudioSubsystem Channels 128
      : >"$STATE/channels-128"
    fi
    # die Sprache gehört dem Spieler, auch wenn die neue Vorlage eine andere hat
    local lang n extra=''
    lang=$(ini_get "$dst.vor-update" Engine.Engine Language)
    [ -z "$lang" ] || set_ini_key "$dst" Engine.Engine Language "$lang"
    n=$(($(grep -ci '^paths=' "$dst" || true) - $(grep -ci '^paths=' "$src" || true)))
    [ "$n" -le 0 ] || extra=", $n eigene Spielpfade (Paths=, z. B. HD-Texturen)"
    msg "SGAlliance.ini auf neue Vorlage gebracht, Grafik/Ton/Sprache$extra ü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
}

# Kopien, deren Vorlage es im Paket nicht mehr gibt (z. B. System/SGGrassBake.ini nach einem Bau
# ohne vorgebackenes Gras): sie würden auf fehlende Dateien zeigen. Unverändert -> löschen,
# vom Spieler oder Spiel geändert -> beiseitelegen (.vor-update).
drop_orphans() {
  local p
  for p in "${!REC[@]}"; do
    [ ! -e "$BASE/$p" ] || continue
    if [ -f "$GAME/$p" ] && [ "$(sha "$GAME/$p")" != "${REC[$p]}" ]; then
      mv -f -- "$GAME/$p" "$GAME/$p.vor-update"
      msg "$p gibt es in der neuen Version nicht mehr, beiseitegelegt: $p.vor-update"
    else
      rm -f -- "$GAME/$p"
    fi
    unset 'REC[$p]'
  done
}

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
  # HD-Texturen gehören zur alten Vorlage: beiseitelegen und beim Start auf der neuen einrichten
  # (sgredial prüft die Dateien und lädt nur, was sich geändert hat)
  local tex lv
  if [ -d "$GAME/SGAlliance/Textures" ] && [ ! -L "$GAME/SGAlliance/Textures" ] && tex=$(helper stargate-redial-textures); then
    lv=$(python3 -I "$tex" stash --game "$GAME" --state "$STATE") || die "HD-Texturen ließen sich nicht beiseitelegen"
    case $lv in 2k | 4k) printf '%s\n' "$lv" >"$STATE/textures-request" ;; esac
  fi
  load_rec
  # verwaiste Links aus einer früheren Version entfernen
  find "$GAME" -maxdepth 3 -xtype l -delete 2>/dev/null || true
  drop_orphans
  link_dir "$BASE" "$GAME" 'System|SGAlliance|SystemARM64|SystemPPC64LE|Installer|.stargate-redial-build'
  link_dir "$BASE/SGAlliance" "$GAME/SGAlliance" 'System|Saves|Server'
  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"
}

# erster Wert von Schlüssel= im Abschnitt (ohne CR), leer wenn es ihn nicht gibt
ini_get() { # Datei Abschnitt Schlüssel
  [ -f "$1" ] || return 0
  awk -v sec="[$2]" -v key="$3" '
    { sub(/\r$/, "") }
    /^\[/ { insec = ($0 == sec); next }
    insec && index($0, key "=") == 1 { v = substr($0, length(key) + 2); sub(/[ \t]+$/, "", v); print v; exit }' "$1"
}

# [Engine.Engine] Language= umstellen; die zweite Language=-Zeile ([Editor.EditorEngine]) bleibt.
# Einen fehlenden Abschnitt legt es nur mit dem fünften Argument an.
set_ini_key() { # Datei Abschnitt Schlüssel Wert [neu]
  local f=$1 tmp
  [ -f "$f" ] || return 0
  tmp=$(mktemp "$f.XXXXXX")
  awk -v sec="[$2]" -v key="$3" -v val="$4" -v neu="${5:-}" '
    { 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 (done) exit
      if (insec) print key "=" val cr
      else if (neu) { print cr; print sec cr; print key "=" val cr } }
  ' "$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)"
}

# --- Sprache ------------------------------------------------------------------------------
# Redial bringt die Übersetzungen seit 0.1.8 selbst mit (*.det Deutsch, *.frt Französisch). Die
# Sprache steht in [Engine.Engine] Language= (int, det, frt). Die Wahl im Spiel (Options ->
# Language) schreibt das Spiel nach [SGShim.SGL10n] Choice=; Redials eigener Starter überträgt sie
# beim nächsten Start nach Language=. Wir starten UT2004.exe direkt und machen das daher selbst.
# Vorrang: --sprache, dann die Wahl im Spiel, dann state/language (ältere Fassungen des Starters).
lang_choice() { # die im Spiel gewählte Sprache (Dateiendung) oder nichts
  local f c
  for f in $LANG_INIS; do
    c=$(ini_get "$GAME/$f" SGShim.SGL10n Choice)
    [[ $c =~ ^[A-Za-z]{3}$ ]] && { printf '%s\n' "${c,,}"; return 0; }
  done
  return 0
}

lang_ext() { case $1 in de) echo det ;; en) echo int ;; fr) echo frt ;; esac; }
has_lang() { [ "$1" = int ] || [ -n "$(echo "$BASE"/SGAlliance/System/*."$1")" ]; }

apply_language() {
  local ini=$GAME/SGAlliance/System/SGAlliance.ini want='' f
  if [ -n "$LANG_SET" ]; then
    want=$(lang_ext "$LANG_SET")
    # ohne Sprachdateien nichts merken, sonst käme die Warnung bei jedem Start wieder
    if ! has_lang "$want"; then
      msg "Warnung: keine Sprachdateien *.$want im Spielordner, die Sprache bleibt"
      return 0
    fi
    printf '%s\n' "$LANG_SET" >"$STATE/language"
    # eine Wahl im Spiel mitziehen, sonst holte der nächste Start sie zurück
    for f in $LANG_INIS; do
      [ -z "$(ini_get "$GAME/$f" SGShim.SGL10n Choice)" ] || set_ini_key "$GAME/$f" SGShim.SGL10n Choice "$want"
    done
  else
    want=$(lang_choice)
    [ -n "$want" ] || want=$(lang_ext "$(cat "$STATE/language" 2>/dev/null)")
  fi
  [ -n "$want" ] || return 0
  if ! has_lang "$want"; then
    msg "Warnung: keine Sprachdateien *.$want im Spielordner, die Sprache bleibt"
    return 0
  fi
  [ "$(ini_get "$ini" Engine.Engine Language)" = "$want" ] && return 0
  set_ini_key "$ini" Engine.Engine Language "$want"
  msg "Sprache: Language=$want"
}

# --- Grafikeffekte (Redial ab 0.1.9) ---------------------------------------------------------
# Redials d3d9.dll (Kantenglättung, Schärfe, Umgebungsverdeckung, Licht je Pixel) liest [SGAA],
# [SGFX] und [SGLight]; die Wahl im Spiel steht in [SGGUI.SGGfxOptions]. Redials eigener Starter
# überträgt sie beim Start. Wir starten UT2004.exe direkt und machen das daher selbst, mit
# denselben Werten (am Starter von 0.1.9 gemessen). Nicht gewählt heißt: Vorgabe der d3d9.dll.
put_ini() { # Datei Abschnitt Schlüssel Wert, nur wenn es sich ändert
  [ "$(ini_get "$1" "$2" "$3")" = "$4" ] || set_ini_key "$1" "$2" "$3" "$4" neu
}
apply_effects() {
  local ini=$1 o=SGGUI.SGGfxOptions v
  [ -e "$GAME/System/d3d9.dll" ] && [ -e "$GAME/SGAlliance/System/SGLightMat.txt" ] || return 0
  put_ini "$ini" $o bEffectsDll True
  v=$(ini_get "$ini" $o AAMode)
  case ${v,,} in
    auto) put_ini "$ini" SGAA Mode Auto ;;
    off) put_ini "$ini" SGAA Mode Off ;;
    post) put_ini "$ini" SGAA Mode Post ;;
    msaa4 | msaa8) put_ini "$ini" SGAA Mode MSAA; put_ini "$ini" SGAA MSAASamples "${v: -1}" ;;
    post+msaa) put_ini "$ini" SGAA Mode Post+MSAA; put_ini "$ini" SGAA MSAASamples 4 ;;
  esac
  v=$(ini_get "$ini" $o Sharpening)
  case ${v,,} in
    off) put_ini "$ini" SGFX Sharpen 0 ;;
    auto) put_ini "$ini" SGFX Sharpen Auto ;;
    light) put_ini "$ini" SGFX Sharpen 0.5 ;;
    strong) put_ini "$ini" SGFX Sharpen 1.0 ;;
  esac
  v=$(ini_get "$ini" $o AmbientOcclusion)
  case ${v,,} in on) put_ini "$ini" SGFX SSAO 1 ;; off) put_ini "$ini" SGFX SSAO 0 ;; esac
  v=$(ini_get "$ini" $o PerPixelLighting)
  case ${v,,} in true) put_ini "$ini" SGLight Enable 1 ;; false) put_ini "$ini" SGLight Enable 0 ;; esac
}

# --- HD-Texturen (Redial ab 0.1.9) ------------------------------------------------------------
# Vorrang: --texturen, dann die Wahl im Spiel (TexturesRequested), dann state/textures-request (vom
# grafischen Installer oder nach einem Paket-Update). Geladen wird mit Redials sgredial.exe.
tex_name() { case $1 in original) echo Original ;; *) echo "${1^^}" ;; esac; }
# Ausgabe von sgredial: im Terminal zeigen, sonst als Fortschrittsfenster (zenity oder kdialog)
tex_progress() { # Stufe; liest Zeilen
  local line n ref='' qd='' title="HD-Texturen (${1^^}) werden geladen und geprüft"
  local re='\[ *([0-9]{1,3})%'
  if [ -t 2 ]; then
    while IFS= read -r line; do
      [[ $line =~ $re || $line == *'[textures]'* ]] && printf '%s\n' "$line" >&2
    done
    return 0
  fi
  if command -v zenity >/dev/null; then
    while IFS= read -r line; do
      [[ $line =~ $re ]] && { n=$((10#${BASH_REMATCH[1]})); echo "$((n > 99 ? 99 : n))"; }
    done | { zenity --progress --title="Stargate Redial" --text="$title" --auto-close --no-cancel --width=420 >/dev/null 2>&1 || cat >/dev/null; }
    return 0
  fi
  if command -v kdialog >/dev/null; then
    for qd in qdbus6 qdbus-qt6 qdbus ''; do [ -z "$qd" ] || ! command -v "$qd" >/dev/null || break; done
    [ -z "$qd" ] || ref=$(kdialog --title "Stargate Redial" --progressbar "$title" 100 2>/dev/null) || ref=''
  fi
  [ -n "$ref" ] || notify "$title"
  while IFS= read -r line; do
    # shellcheck disable=SC2086
    [ -z "$ref" ] || ! [[ $line =~ $re ]] || "$qd" $ref Set '' value "$((10#${BASH_REMATCH[1]}))" >/dev/null 2>&1 || true
  done
  # shellcheck disable=SC2086
  [ -z "$ref" ] || "$qd" $ref close >/dev/null 2>&1 || true
}
install_textures() { # 2k|4k
  local tex=$1 lv=$2 exe=$GAME/SGAlliance/Launcher/app/tools/sgredial.exe err rc=0 wp
  [ -f "$exe" ] || { msg "HD-Texturen: sgredial.exe fehlt im Spielordner (älteres Paket), bitte neu bauen"; return 1; }
  err=$(python3 -I "$tex" prepare --game "$GAME" --base "$BASE" --state "$STATE" "$lv" 2>&1) || rc=$?
  if [ "$rc" -eq 3 ]; then
    err="HD-Texturen ${lv^^}: zu wenig Platz (nötig und frei in GB: ${err##*: })"
    msg "$err"; notify "$err"; return 1
  elif [ "$rc" -ne 0 ]; then
    msg "HD-Texturen: $err"; notify "HD-Texturen: $err"; return 1
  fi
  wp=$(realpath -m -- "$GAME"); wp="Z:${wp//\//\\}"
  setup_runner
  msg "HD-Texturen ${lv^^}: laden und prüfen (Protokoll: $STATE/textures.log)"
  "${RUN[@]}" "$exe" --textures-only "$lv" --ut2004 "$wp" --no-update-check </dev/null 2>&1 9>&- |
    tr '\r' '\n' | tee "$STATE/textures.log" | tex_progress "$lv" || true
  [ "$(python3 -I "$tex" level --game "$GAME")" = "$lv" ] && { msg "HD-Texturen ${lv^^} eingerichtet"; return 0; }
  err="HD-Texturen ${lv^^} ließen sich nicht einrichten, das Spiel läuft mit den bisherigen weiter (Protokoll: $STATE/textures.log)"
  msg "$err"; notify "$err"
  return 1
}
apply_textures() {
  local ini=$1 o=SGGUI.SGGfxOptions tex have want name
  tex=$(helper stargate-redial-textures) && command -v python3 >/dev/null && [ -f "$ini" ] || return 0
  have=$(python3 -I "$tex" level --game "$GAME") || return 0
  want=$TEX_SET
  if [ -z "$want" ]; then
    want=$(ini_get "$ini" $o TexturesRequested)
    [ -n "$want" ] || want=$(cat "$STATE/textures-request" 2>/dev/null || true)
    want=${want,,}
    case $want in original | 2k | 4k) ;; *) want=$have ;; esac
    # nur einrichten heißt: ohne ausdrückliche Wahl nichts laden
    [ "$SETUP_ONLY" -eq 0 ] || want=$have
  fi
  if [ "$want" != "$have" ] || { [ -n "$TEX_SET" ] && [ "$want" != original ]; }; then
    if [ "$want" = original ]; then
      python3 -I "$tex" reset --game "$GAME" && link_dir "$BASE/SGAlliance" "$GAME/SGAlliance" 'System|Saves|Server' &&
        ln -sfn -- "$BASE/SGAlliance/System/SGLight.txt" "$GAME/SGAlliance/System/SGLight.txt"
      rm -rf -- "$STATE/hd-stash"
      msg "HD-Texturen entfernt, es gelten die Originale von 2005"
    else
      install_textures "$tex" "$want" || want=''
    fi
  fi
  if [ -n "$want" ] && { [ "$SETUP_ONLY" -eq 0 ] || [ -n "$TEX_SET" ]; }; then
    rm -f -- "$STATE/textures-request"
    [ -z "$(ini_get "$ini" $o TexturesRequested)" ] || set_ini_key "$ini" $o TexturesRequested ''
  fi
  name=$(tex_name "$(python3 -I "$tex" level --game "$GAME")")
  # Anzeige im Spiel (Options -> Video); Spielordner vor 0.1.9 kennen den Schlüssel nicht
  [ ! -d "$BASE/SGAlliance/.redial" ] || put_ini "$ini" $o TexturePack "$name"
}

apply_settings() {
  local ini=$GAME/SGAlliance/System/SGAlliance.ini
  apply_language
  [ "$WINDOWED" -eq 0 ] || set_ini_key "$ini" WinDrv.WindowsClient StartupFullscreen False
  apply_resolution "$ini"
  apply_textures "$ini"
  apply_effects "$ini"
}

# --- Start ------------------------------------------------------------------------------
RUN=()
setup_runner() { # füllt RUN und die Umgebung
  [ ${#RUN[@]} -eq 0 ] || return 0
  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)"
    RUN=(umu-run)
  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
    # d3d9=n,b: Redials d3d9.dll neben dem Spiel (Effekte, ab 0.1.9); Proton nimmt sie von selbst
    export WINEDLLOVERRIDES=${WINEDLLOVERRIDES:-mscoree=d;mshtml=d;winemenubuilder.exe=d;d3d9=n,b}
    export WINEDEBUG=${WINEDEBUG:--all}
    RUN=("$wine")
  fi
  mkdir -p -- "$WINEPREFIX"
}
launch() {
  local cmd
  setup_runner
  cmd=("${RUN[@]}" "$GAME/System/UT2004.exe")
  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
