#!/usr/bin/env bash
# Egress on a Steam Deck (or any x86_64 Linux): install, update, launch.
#
#   curl -fsSL https://static.alcaas.co.uk/sf2/egress-deck.sh | bash        # first install (Desktop Mode)
#   ~/Games/egress-deck.sh run [game args]                                  # what the Steam shortcut runs
#   ~/Games/egress-deck.sh update                                           # update without starting the game
#   ~/Games/egress-deck.sh steam                                            # (re)add the Steam shortcut and its artwork
#
# "run" checks the server for a newer Linux build (a few seconds at most, skipped when offline), installs it, then
# starts the game fullscreen. Saves live in ~/.local/share/godot/app_userdata/Egress and are never touched by an update.
# Personal playtest script: not part of the repository.
set -uo pipefail

BASE=${EGRESS_BASE:-https://static.alcaas.co.uk/sf2}
ROOT=${EGRESS_ROOT:-$HOME/Games}
DIR=$ROOT/egress
SELF=$ROOT/egress-deck.sh
LOG=$ROOT/egress-last.log
ART=$ROOT/egress-art
HELPER=$ROOT/egress_steam.py
ART_FILES="icon.png capsule.png wide.png background.png logo.png"
ROM_NAME="Shining Force II (USA).gen"
ROM_SHA=9adf662d09881f58ec37d174ab01e87a7fcfb24700b5f84b26c0cd4f351509e9

say() { echo "egress: $*" >&2; }
have() { command -v "$1" >/dev/null 2>&1; }

unpack() {   # unpack ZIP DEST
  if have unzip; then unzip -q "$1" -d "$2"
  elif have bsdtar; then bsdtar -xf "$1" -C "$2"
  else python3 -I -m zipfile -e "$1" "$2"; fi
}

# A progress window when there is a screen and zenity (Game Mode shows it too), else plain curl output.
fetch() {    # fetch URL FILE TITLE
  if [[ -n ${DISPLAY:-}${WAYLAND_DISPLAY:-} ]] && have zenity && [[ ! -t 2 ]]; then
    curl -fL --connect-timeout 5 -o "$2" "$1" 2>&1 \
      | stdbuf -oL tr '\r' '\n' | sed -u -n 's/^ *\([0-9]\+\) .*/\1/p' \
      | zenity --progress --auto-close --no-cancel --title=Egress --text="$3" 2>/dev/null
    [[ -s $2 ]]
  else
    say "$3"
    curl -fL --connect-timeout 5 --progress-bar -o "$2" "$1"
  fi
}

# The Steam artwork and the helper that adds the shortcut (small files; refreshed whenever the server is reachable).
fetch_art() {
  mkdir -p "$ART"
  local f
  for f in $ART_FILES; do
    curl -fsS --connect-timeout 3 --max-time 20 -o "$ART/$f.part" "$BASE/art/$f" && mv "$ART/$f.part" "$ART/$f"
    rm -f "$ART/$f.part"
  done
  curl -fsS --connect-timeout 3 --max-time 20 -o "$HELPER.part" "$BASE/egress_steam.py" \
    && python3 -I -m py_compile "$HELPER.part" 2>/dev/null && mv "$HELPER.part" "$HELPER"
  rm -f "$HELPER.part"
}

ensure_rom() {
  local rom=$DIR/$ROM_NAME
  [[ -f $rom ]] && return 0
  local tmp=$ROOT/.egress-rom.part
  fetch "$BASE/SF2.gen" "$tmp" "Downloading the ROM" || { rm -f "$tmp"; say "could not download the ROM"; return 1; }
  if [[ $(sha256sum "$tmp" | cut -d' ' -f1) != "$ROM_SHA" ]]; then rm -f "$tmp"; say "the ROM's checksum is wrong"; return 1; fi
  mv "$tmp" "$rom"
}

update() {
  mkdir -p "$ROOT"
  local latest installed=""
  latest=$(curl -fsS --connect-timeout 3 --max-time 8 "$BASE/linux/VERSION" | tr -d '[:space:]') || latest=""
  [[ -f $DIR/VERSION ]] && installed=$(<"$DIR/VERSION")

  # Keep this script current too (takes effect from the next launch).
  local s=$ROOT/.egress-deck.sh.part
  if [[ -n $latest ]] && curl -fsS --connect-timeout 3 --max-time 8 -o "$s" "$BASE/egress-deck.sh" && bash -n "$s"; then
    cmp -s "$s" "$SELF" || { chmod +x "$s"; mv "$s" "$SELF"; }
  fi
  rm -f "$s"
  [[ -n $latest ]] && fetch_art

  if [[ -z $latest ]]; then
    [[ -x $DIR/EgressHost.x86_64 ]] && { say "offline; playing ${installed:-the installed build}"; return 0; }
    say "cannot reach $BASE and nothing is installed"; return 1
  fi
  if [[ $latest == "$installed" && -x $DIR/EgressHost.x86_64 ]]; then
    say "up to date ($installed)"
  else
    local work zip
    work=$(mktemp -d "$ROOT/.egress-update-XXXXXX")
    zip=$work/build.zip
    if fetch "$BASE/linux/Egress-linux-x86_64.zip" "$zip" "Downloading Egress $latest" \
       && (cd "$work" && curl -fsS "$BASE/linux/Egress-linux-x86_64.zip.sha256" | sed 's/ .*/  build.zip/' | sha256sum -c --quiet) \
       && unpack "$zip" "$work/x"; then
      local new=$work/x/Egress-linux-x86_64
      [[ -f $DIR/$ROM_NAME ]] && cp "$DIR/$ROM_NAME" "$new/"
      echo "$latest" > "$new/VERSION"
      rm -rf "$DIR.old"; [[ -d $DIR ]] && mv "$DIR" "$DIR.old"
      mv "$new" "$DIR" && rm -rf "$DIR.old"
      say "installed $latest${installed:+ (was $installed)}"
    else
      say "update to $latest failed; keeping ${installed:-nothing}"
    fi
    rm -rf "$work"
  fi
  ensure_rom
}

register() {
  local apps=$HOME/.local/share/applications desktop
  mkdir -p "$apps"
  desktop=$apps/egress.desktop
  cat > "$desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Egress
Comment=Shining Force II, reimplemented (playtest build)
Exec="$SELF" run
Path=$DIR
Icon=$ART/icon.png
Terminal=false
Categories=Game;
EOF
  chmod +x "$desktop"
  [[ -f $HELPER ]] || fetch_art
  # The shortcut is written into Steam's shortcuts.vdf, which Steam only accepts while it is closed: the helper closes it
  # and starts it again (Desktop Mode), then puts the artwork in Steam's grid folder.
  if [[ -f $HELPER ]] && have python3 \
     && python3 -I "$HELPER" --exe "$SELF" --launch-options run --start-dir "$DIR" --art "$ART" --restart-steam; then
    say "added to Steam as \"Egress\" with its artwork (Library > Non-Steam)"
  elif have steamos-add-to-steam; then
    steamos-add-to-steam "$desktop" && say "added to Steam as \"Egress\" (Library > Non-Steam); artwork on the next launch"
  else
    say "add it to Steam by hand: Steam > Games > Add a Non-Steam Game > Egress"
  fi
}

# On every launch: put the artwork in place for the shortcut Steam already has (no restart needed; it shows the next
# time Steam loads the library). The shortcut itself is only rewritten by "steam" or "install".
refresh_art() {
  [[ -f $HELPER ]] && have python3 || return 0
  python3 -I "$HELPER" --exe "$SELF" --launch-options run --start-dir "$DIR" --art "$ART" >>"$LOG" 2>&1 || true
}

install() {
  mkdir -p "$ROOT"
  # Piped through bash there is no file to copy, so save the server's copy as the launcher.
  if [[ ${BASH_SOURCE[0]:-} != "$SELF" ]]; then
    curl -fsS "$BASE/egress-deck.sh" -o "$SELF.part" && chmod +x "$SELF.part" && mv "$SELF.part" "$SELF" \
      || { say "could not save the launcher"; return 1; }
  fi
  update || return 1
  register
  say "done. Play it from Steam (Game Mode) or run: $SELF run"
}

run() {
  update >"$LOG" 2>&1 || { cat "$LOG" >&2; }
  refresh_art
  [[ -x $DIR/EgressHost.x86_64 ]] || { say "not installed; see $LOG"; exit 1; }
  echo "--- $(date) $(cat "$DIR/VERSION" 2>/dev/null)" >>"$LOG"
  cd "$DIR" && exec ./EgressHost.x86_64 --fullscreen "$@" >>"$LOG" 2>&1
}

cmd=${1:-install}; [[ $# -gt 0 ]] && shift
case $cmd in
  install) install ;;
  update) update ;;
  run) run "$@" ;;
  steam) fetch_art; register ;;
  *) echo "usage: $0 [install|update|steam|run [game args]]" >&2; exit 2 ;;
esac
