#!/usr/bin/env bash
# Updraft on a Steam Deck: installs the Linux build from the static host, adds it to Steam, and fetches the newest build
# each time it is launched. It is for the owner's own playtesting, so it stays simple. See packaging/deck/README.md.
#
# First time, in Desktop mode, in Konsole:
#   curl -fsSL https://static.alcaas.co.uk/updraft/deck/updraft-deck.sh | bash -s install
# Then play "Updraft" from the Steam library, in Game mode too.
#
#   updraft-deck.sh install [TRACK]  keep a copy of this script, install the newest build, add the Steam shortcut
#   updraft-deck.sh track [TRACK]    show the track, or switch to another one and fetch its build
#   updraft-deck.sh update           fetch the track's newest build, if it isn't installed yet
#   updraft-deck.sh launch [ARGS]    what the Steam shortcut runs: update (if online), then play
#   updraft-deck.sh list             builds on the host, and the installed ones
#   updraft-deck.sh reports          open the folder that F8 / holding Start saves reports into
#   updraft-deck.sh art [PROGRAM]    give the Steam shortcut its artwork and icon (restarts Steam if you say so)
#   updraft-deck.sh pick TRACK       (for tests) print the version folders of an index page on stdin, newest first
#
# TRACK is `latest` (the default: the newest version, betas included), `stable` (no prereleases), or the name of a
# folder on the host, such as a requested build (`lark-levels`) or one version (`v0.4.0`), which pins it.
set -euo pipefail

BASE_URL=${UPDRAFT_BASE_URL:-https://static.alcaas.co.uk/updraft}
UPDRAFT_HOME=${UPDRAFT_HOME:-$HOME/Games/updraft}
SCRIPT_URL="$BASE_URL/deck/updraft-deck.sh"
ISSUE_URL="https://github.com/alexwlsnr/updraft/issues/new?template=playtest.yml"
# Installed builds kept besides the current one, to go back to with `track <folder>` while offline.
KEEP_OLD=1

say() { printf 'updraft-deck: %s\n' "$*" >&2; }

# Launched from Steam there is no terminal, so messages and progress go to zenity dialogs (SteamOS has zenity).
gui() { ! [ -t 2 ] && [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; }

die() {
  say "$*"
  if gui; then zenity --error --title=Updraft --text="$*" >/dev/null 2>&1 || true; fi
  exit 1
}

fetch() { curl -fsS --connect-timeout 8 -m 20 "$1"; }

current_track() { cat "$UPDRAFT_HOME/track" 2>/dev/null || echo latest; }

check_track() {
  [[ $1 =~ ^[a-z0-9][a-z0-9._-]*$ ]] || die "'$1' isn't a track: use latest, stable or a folder name from \`list\`"
}

# The version folders in an index page (stdin), newest first. `stable` leaves out the -alpha/-beta/-rc ones.
pick() {
  local track=$1
  { grep -oE 'href="v[0-9]+\.[0-9]+\.[0-9]+(-(alpha|beta|rc)\.[0-9]+)?/"' || true; } \
    | sed -E 's/^href="//; s|/"$||' \
    | awk -v track="$track" '{
        v = substr($0, 2); pre = ""; rank = 9; n = 0
        i = index(v, "-")
        if (i) { pre = substr(v, i + 1); v = substr(v, 1, i - 1) }
        if (track == "stable" && pre != "") next
        split(v, p, ".")
        if (pre != "") { split(pre, q, "."); rank = (q[1] == "alpha" ? 1 : (q[1] == "beta" ? 2 : 3)); n = q[2] }
        printf "%d %d %d %d %d %s\n", p[1], p[2], p[3], rank, n, $0
      }' \
    | sort -u -k1,1nr -k2,2nr -k3,3nr -k4,4nr -k5,5nr \
    | awk '{ print $6 }'
}

# The other folders on the host: requested builds such as `lark-levels`.
labels() {
  { grep -oE 'href="[a-z0-9][a-z0-9._-]*/"' || true; } | sed -E 's/^href="//; s|/"$||' \
    | grep -vE '^v[0-9]+\.[0-9]+\.[0-9]+(-(alpha|beta|rc)\.[0-9]+)?$|^deck$' || true
}

# The Linux archive's file name in a folder on the host, or nothing.
tarball_in() {
  { fetch "$BASE_URL/$1/" || true; } | { grep -oE 'href="updraft-[^"/]*-linux-x86_64\.tar\.gz"' || true; } \
    | head -n 1 | sed -E 's/^href="//; s/"$//'
}

# "FOLDER ARCHIVE" for a track: for latest and stable, the newest version folder that has a Linux build yet.
resolve() {
  local track=$1 index folder tar
  case $track in
    latest | stable)
      index=$(fetch "$BASE_URL/") || return 1
      for folder in $(pick "$track" <<<"$index"); do
        tar=$(tarball_in "$folder")
        if [ -n "$tar" ]; then echo "$folder $tar"; return 0; fi
      done
      ;;
    *)
      tar=$(tarball_in "$track")
      if [ -n "$tar" ]; then echo "$track $tar"; return 0; fi
      ;;
  esac
  return 1
}

# Download FOLDER/ARCHIVE and unpack it into builds/NAME (the archive holds one folder, NAME).
download() {
  local url="$BASE_URL/$1" name=$2 tmp ok=0
  mkdir -p "$UPDRAFT_HOME/builds"
  tmp=$(mktemp -d "$UPDRAFT_HOME/.download.XXXXXX")
  say "downloading $url"
  if gui; then
    { curl -fL -sS --connect-timeout 8 -o "$tmp/build.tar.gz" "$url" && touch "$tmp/ok"; echo 100; } 2>"$tmp/err" \
      | zenity --progress --pulsate --auto-close --no-cancel --title=Updraft --text="Downloading $name…" \
        >/dev/null 2>&1 || true
    [ -f "$tmp/ok" ] || cat "$tmp/err" >&2
  else
    curl -fL --progress-bar --connect-timeout 8 -o "$tmp/build.tar.gz" "$url" && touch "$tmp/ok"
  fi
  if [ -f "$tmp/ok" ]; then
    mkdir "$tmp/x"
    if tar -xzf "$tmp/build.tar.gz" -C "$tmp/x" && [ -x "$tmp/x/$name/updraft" ]; then
      rm -rf "${UPDRAFT_HOME:?}/builds/$name"
      mv "$tmp/x/$name" "$UPDRAFT_HOME/builds/$name"
      touch "$UPDRAFT_HOME/builds/$name"
      ok=1
    else
      say "the archive doesn't hold $name/updraft"
    fi
  fi
  rm -rf "$tmp"
  [ "$ok" = 1 ]
}

use_build() { ln -sfn "builds/$1" "$UPDRAFT_HOME/current"; }

# Delete installed builds other than the current one and the KEEP_OLD newest.
prune() {
  local cur d kept=0
  cur=$(readlink "$UPDRAFT_HOME/current" || true)
  for d in $(ls -1t "$UPDRAFT_HOME/builds"); do
    [ "builds/$d" = "$cur" ] && continue
    kept=$((kept + 1))
    [ "$kept" -le "$KEEP_OLD" ] && continue
    say "removing old build $d"
    rm -rf -- "${UPDRAFT_HOME:?}/builds/$d"
  done
}

update() {
  local track found folder tar name
  track=$(current_track)
  found=$(resolve "$track") || { say "no Linux build for '$track' at $BASE_URL (offline?)"; return 1; }
  read -r folder tar <<<"$found"
  name=${tar%.tar.gz}
  if [ -x "$UPDRAFT_HOME/builds/$name/updraft" ]; then
    use_build "$name"
    say "up to date: $name"
    return 0
  fi
  download "$folder/$tar" "$name" || { say "couldn't download $name"; return 1; }
  use_build "$name"
  prune
  say "installed $name"
}

track() {
  if [ $# -eq 0 ]; then current_track; return; fi
  check_track "$1"
  mkdir -p "$UPDRAFT_HOME"
  echo "$1" >"$UPDRAFT_HOME/track"
  update
}

launch() {
  update || say "playing the installed build"
  [ -x "$UPDRAFT_HOME/current/updraft" ] || die "No Updraft build is installed, and none could be downloaded. Are you online?"
  cd "$UPDRAFT_HOME/current"
  exec ./updraft "$@"
}

install() {
  local track=${1:-latest} self
  check_track "$track"
  mkdir -p "$UPDRAFT_HOME"
  # A copy of this script to launch from. Run as `curl ... | bash`, there is no file to copy, so fetch it again.
  self=${BASH_SOURCE[0]:-}
  if [ -f "$self" ]; then
    if [ "$(realpath "$self")" != "$(realpath -m "$UPDRAFT_HOME/updraft-deck.sh")" ]; then
      cp "$self" "$UPDRAFT_HOME/updraft-deck.sh"
    fi
  else
    fetch "$SCRIPT_URL" >"$UPDRAFT_HOME/.updraft-deck.sh.new"
    mv "$UPDRAFT_HOME/.updraft-deck.sh.new" "$UPDRAFT_HOME/updraft-deck.sh"
  fi
  chmod +x "$UPDRAFT_HOME/updraft-deck.sh"
  # What Steam runs. Its file name is the name the shortcut gets.
  printf '#!/bin/sh\nexec "%s/updraft-deck.sh" launch "$@"\n' "$UPDRAFT_HOME" >"$UPDRAFT_HOME/Updraft"
  chmod +x "$UPDRAFT_HOME/Updraft"
  echo "$track" >"$UPDRAFT_HOME/track"
  update || die "couldn't install a build for '$track'"

  fetch_art || say "couldn't fetch the Steam artwork; carrying on without it"

  if [ -f "$UPDRAFT_HOME/.added-to-steam" ]; then
    say "already in Steam (delete $UPDRAFT_HOME/.added-to-steam to add it again)"
  elif command -v steamos-add-to-steam >/dev/null 2>&1; then
    steamos-add-to-steam "$UPDRAFT_HOME/Updraft"
    touch "$UPDRAFT_HOME/.added-to-steam"
    say "added \"Updraft\" to Steam"
  else
    say "add it to Steam by hand: Games > Add a Non-Steam Game > Browse > $UPDRAFT_HOME/Updraft"
    say "then run \`$UPDRAFT_HOME/updraft-deck.sh art\` for its artwork"
  fi
  if [ -f "$UPDRAFT_HOME/.added-to-steam" ]; then art || true; fi
  say "done. Play \"Updraft\" from Steam; each launch fetches the newest '$track' build first."
}

# The library pictures and the helper that installs them (packaging/deck/steam_art.py), from the host.
fetch_art() {
  local f
  mkdir -p "$UPDRAFT_HOME/art"
  fetch "$BASE_URL/deck/steam_art.py" >"$UPDRAFT_HOME/.steam_art.py.new"
  mv "$UPDRAFT_HOME/.steam_art.py.new" "$UPDRAFT_HOME/steam_art.py"
  for f in capsule wide hero logo icon; do
    fetch "$BASE_URL/deck/art/$f.png" >"$UPDRAFT_HOME/art/.$f.png.new"
    mv "$UPDRAFT_HOME/art/.$f.png.new" "$UPDRAFT_HOME/art/$f.png"
  done
}

# Copy the artwork into Steam for the shortcut that runs PROGRAM (default: this install's launcher). The pictures show
# once Steam restarts; the icon can only be set while Steam is closed, so offer to restart it.
art() {
  local exe=${1:-$UPDRAFT_HOME/Updraft} helper=(python3 "$UPDRAFT_HOME/steam_art.py" --art "$UPDRAFT_HOME/art")
  local status=0 answer
  [ -f "$UPDRAFT_HOME/steam_art.py" ] || fetch_art || { say "couldn't fetch the artwork"; return 1; }
  "${helper[@]}" --exe "$exe" --wait 20 --icon || status=$?
  case $status in
    0) say "artwork set; it shows after Steam restarts" ;;
    3)
      if [ -t 0 ] && [ -t 2 ]; then
        read -r -p "updraft-deck: restart Steam now to set the icon and show the artwork? [Y/n] " answer
        case ${answer:-y} in
          [Yy]*)
            steam -shutdown >/dev/null 2>&1 || true
            for _ in $(seq 60); do pgrep -x steam >/dev/null || break; sleep 1; done
            if pgrep -x steam >/dev/null; then say "Steam didn't close; run \`$UPDRAFT_HOME/updraft-deck.sh art\` later"; return 1; fi
            "${helper[@]}" --exe "$exe" --icon || true
            setsid -f steam >/dev/null 2>&1 </dev/null
            say "Steam restarted with the artwork"
            ;;
          *) say "pictures copied; quit Steam and run \`$UPDRAFT_HOME/updraft-deck.sh art\` again to set the icon" ;;
        esac
      else
        say "pictures copied; quit Steam and run \`$UPDRAFT_HOME/updraft-deck.sh art\` again to set the icon"
      fi
      ;;
    *) say "couldn't find the Steam shortcut for $exe"; return 1 ;;
  esac
}

list() {
  local index cur d
  index=$(fetch "$BASE_URL/") || die "can't reach $BASE_URL"
  say "versions on the host, newest first:"
  pick latest <<<"$index" | head -n 8 | sed 's/^/  /' >&2
  say "requested builds:"
  labels <<<"$index" | sed 's/^/  /' >&2
  say "installed (track: $(current_track)):"
  cur=$(readlink "$UPDRAFT_HOME/current" 2>/dev/null || true)
  for d in $(ls -1t "$UPDRAFT_HOME/builds" 2>/dev/null); do
    if [ "builds/$d" = "$cur" ]; then say "  $d  (current)"; else say "  $d"; fi
  done
}

reports() {
  local data=${XDG_DATA_HOME:-$HOME/.local/share} d found=""
  for d in "$data/updraftskyschool(testing)/reports" "$data/updraftskyschool/reports"; do
    if [ -d "$d" ]; then
      say "$d:"
      ls -1t "$d" | head -n 5 | sed 's/^/  /' >&2
      found=${found:-$d}
    fi
  done
  [ -n "$found" ] || die "no reports yet (press F8 or hold Start for 2 seconds in the game)"
  say "file them at $ISSUE_URL"
  if command -v xdg-open >/dev/null 2>&1; then xdg-open "$found" >/dev/null 2>&1 || true; fi
}

cmd=${1:-}
[ $# -gt 0 ] && shift
case $cmd in
  install) install "$@" ;;
  track) track "$@" ;;
  update) update ;;
  launch) launch "$@" ;;
  list) list ;;
  reports) reports ;;
  art) art "$@" ;;
  pick) pick "${1:-latest}" ;;
  *)
    say "usage: updraft-deck.sh install|track|update|launch|list|reports (see the comment at the top of the script)"
    exit 2
    ;;
esac
