#!/usr/bin/env bash
# Trade Routes Online Linux installer / updater.
# Same role as TRO_Installer.exe on Windows: read latest.json, download the game
# payload for this arch, install to a per-user folder, write a desktop entry, and
# (with --auto) relaunch after an in-game update.
#
# Shipped names (identical script; arch pinned by basename):
#   TRO_Installer_linux_x64.sh
#   TRO_Installer_linux_arm64.sh
#
# Usage:
#   ./TRO_Installer_linux_arm64.sh              # interactive install/update
#   ./TRO_Installer_linux_arm64.sh --auto       # from the game: update + relaunch
#   ./TRO_Installer_linux_x64.sh --prefix DIR --no-launch --file /path/to/game.tar.gz
#   ./TRO_Installer_linux_x64.sh --manifest URL
#
# Env: TRO_MANIFEST_URL, TRO_INSTALL_DIR, TRO_DOWNLOAD_BASE
set -euo pipefail

APP_NAME="Trade Routes Online"
APP_ID="trade-routes-online"
DEFAULT_MANIFEST="${TRO_MANIFEST_URL:-https://traderoutesonline.com/tro/download/latest.json}"
DEFAULT_BASE="${TRO_DOWNLOAD_BASE:-https://traderoutesonline.com/tro/download}"
DEFAULT_DIR="${TRO_INSTALL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/TradeRoutesOnline}"

manifest_url="$DEFAULT_MANIFEST"
prefix=""
local_file=""
auto=0
no_launch=0
keep_going=0

usage() {
  sed -n '1,20p' "$0" | sed 's/^# \{0,1\}//'
  exit 0
}

log() { printf '%s\n' "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }

arch_from_basename() {
  case "$(basename "$0")" in
    *arm64*) echo arm64 ;;
    *x64*|*amd64*) echo x64 ;;
    *) echo "" ;;
  esac
}

detect_arch() {
  local forced pin
  pin="$(arch_from_basename)"
  if [[ -n "$pin" ]]; then echo "$pin"; return; fi
  case "$(uname -m)" in
    x86_64|amd64) echo x64 ;;
    aarch64|arm64) echo arm64 ;;
    *) die "unsupported CPU $(uname -m). Need x86_64 or aarch64." ;;
  esac
}

# Very small JSON string getter (no jq required). Reads one top-level or platforms.<key>.<field> string/number.
json_get() {
  # usage: json_get "$json" field           OR json_get "$json" platforms KEY field
  local json="$1"
  if [[ $# -eq 2 ]]; then
    python3 - "$json" "$2" <<'PY' 2>/dev/null || true
import json,sys
j=json.loads(sys.argv[1]); v=j.get(sys.argv[2]); print("" if v is None else v)
PY
  else
    python3 - "$json" "$2" "$3" "$4" <<'PY' 2>/dev/null || true
import json,sys
j=json.loads(sys.argv[1])
plat=(j.get("platforms") or {}).get(sys.argv[3]) or {}
v=plat.get(sys.argv[4])
if v is None and sys.argv[4] in ("file","sha256","size","exe","installer"):
    pass
print("" if v is None else v)
PY
  fi
}

download() {
  local url="$1" dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fL --retry 3 --retry-delay 2 -o "$dest" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -O "$dest" "$url"
  else
    die "need curl or wget to download"
  fi
}

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'
  else echo ""; fi
}

wait_for_game_exit() {
  local tries=60
  while (( tries-- > 0 )); do
    if ! pgrep -f '[t]rade-routes-online' >/dev/null 2>&1; then return 0; fi
    sleep 1
  done
  log "warning: trade-routes-online still running; installing anyway (files in use may fail)"
}

install_icon() {
  local src="$1"
  local icondir="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
  mkdir -p "$icondir"
  if [[ -f "$src" ]]; then
    cp -f "$src" "$icondir/${APP_ID}.png"
    return 0
  fi
  # Host copy Claude uploads next to the installers
  local tmp
  tmp="$(mktemp)"
  if download "${download_base}/trade-routes-online.png" "$tmp" 2>/dev/null; then
    cp -f "$tmp" "$icondir/${APP_ID}.png"
    rm -f "$tmp"
    return 0
  fi
  rm -f "$tmp"
  return 1
}

write_desktop() {
  local dir="$1" exe="$2"
  local apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
  local icon_path="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps/${APP_ID}.png"
  mkdir -p "$apps"
  local icon_field="$APP_ID"
  [[ -f "$icon_path" ]] && icon_field="$icon_path"
  cat > "$apps/${APP_ID}.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=${APP_NAME}
Comment=First-person multiplayer medieval trading game
Exec=${dir}/${exe}
Path=${dir}
Icon=${icon_field}
Terminal=false
Categories=Game;
StartupNotify=true
DESKTOP
  chmod 644 "$apps/${APP_ID}.desktop"
  # Refresh desktop database when the tool exists (ignore failures)
  command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 || true
  log "menu entry: $apps/${APP_ID}.desktop"
}

# ---- args ----
while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help) usage ;;
    --auto|/auto) auto=1; shift ;;
    --no-launch) no_launch=1; shift ;;
    --prefix|--dir) prefix="${2:-}"; shift 2 ;;
    --prefix=*|--dir=*) prefix="${1#*=}"; shift ;;
    --file) local_file="${2:-}"; shift 2 ;;
    --file=*) local_file="${1#*=}"; shift ;;
    --manifest) manifest_url="${2:-}"; shift 2 ;;
    --manifest=*) manifest_url="${1#*=}"; shift ;;
    *) die "unknown argument: $1" ;;
  esac
done

ARCH="$(detect_arch)"
KEY="linux-${ARCH}"
INSTALL_DIR="${prefix:-$DEFAULT_DIR}"
download_base="$DEFAULT_BASE"
# If manifest URL is under .../download/latest.json, base is its directory
if [[ "$manifest_url" == *'/latest.json' ]]; then
  download_base="${manifest_url%/latest.json}"
fi

log "$APP_NAME Linux installer (${KEY})"
log "install dir: $INSTALL_DIR"

TMP="$(mktemp -d "${TMPDIR:-/tmp}/tro-install.XXXXXX")"
cleanup() { rm -rf "$TMP"; }
trap cleanup EXIT

GAME_TAR=""
VERSION=""
EXE="trade-routes-online"
SHA=""

if [[ -n "$local_file" ]]; then
  [[ -f "$local_file" ]] || die "file not found: $local_file"
  GAME_TAR="$local_file"
  VERSION="local"
  log "using local package: $GAME_TAR"
else
  log "manifest: $manifest_url"
  MJSON="$TMP/latest.json"
  download "$manifest_url" "$MJSON" || die "could not download latest.json"
  VERSION="$(json_get "$(cat "$MJSON")" version)"
  [[ -n "$VERSION" ]] || die "manifest has no version"
  FILE="$(json_get "$(cat "$MJSON")" platforms "$KEY" file)"
  SHA="$(json_get "$(cat "$MJSON")" platforms "$KEY" sha256)"
  EXE_J="$(json_get "$(cat "$MJSON")" platforms "$KEY" exe)"
  [[ -n "$EXE_J" ]] && EXE="$EXE_J"
  if [[ -z "$FILE" ]]; then
    if [[ "$ARCH" == "x64" ]]; then FILE="TradeRoutesOnline-${VERSION}-x64.tar.gz"
    else FILE="TradeRoutesOnline-${VERSION}-arm64.tar.gz"; fi
  fi
  GAME_TAR="$TMP/$FILE"
  log "downloading $FILE …"
  download "${download_base}/${FILE}" "$GAME_TAR" || die "download failed: ${download_base}/${FILE}"
  if [[ -n "$SHA" ]]; then
    got="$(sha256_of "$GAME_TAR")"
    [[ -n "$got" ]] || die "no sha256 tool on this system"
    [[ "${got,,}" == "${SHA,,}" ]] || die "checksum mismatch for $FILE"
    log "checksum ok"
  fi
fi

# Extract: electron-builder tar.gz is usually one top folder TradeRoutesOnline-<ver>-<arch>/
STAGE="$TMP/stage"
mkdir -p "$STAGE"
log "extracting…"
tar -xzf "$GAME_TAR" -C "$STAGE"
# Find the folder that contains the game binary
SRC="$(find "$STAGE" -type f -name "$EXE" 2>/dev/null | head -n1 || true)"
[[ -n "$SRC" ]] || SRC="$(find "$STAGE" -type f -name 'trade-routes-online' 2>/dev/null | head -n1 || true)"
[[ -n "$SRC" ]] || die "package has no trade-routes-online binary"
SRC_DIR="$(cd "$(dirname "$SRC")" && pwd)"

if (( auto )); then wait_for_game_exit; fi

mkdir -p "$INSTALL_DIR"
# Replace contents but keep the install dir itself (in-place update)
log "installing into $INSTALL_DIR …"
# Remove previous app files except a few markers we may add
find "$INSTALL_DIR" -mindepth 1 -maxdepth 1 ! -name 'install.log' -exec rm -rf {} +
cp -a "$SRC_DIR"/. "$INSTALL_DIR"/
chmod +x "$INSTALL_DIR/$EXE" 2>/dev/null || true
# chrome-sandbox may need setuid on some systems; leave as packaged
printf '%s\n' "$VERSION" > "$INSTALL_DIR/tro-version.txt"
printf '%s\n' "$KEY" > "$INSTALL_DIR/tro-platform.txt"

# Icon: prefer one shipped beside this script, else download from host
ICON_SRC=""
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
[[ -f "$SCRIPT_DIR/trade-routes-online.png" ]] && ICON_SRC="$SCRIPT_DIR/trade-routes-online.png"
install_icon "${ICON_SRC:-}" || log "note: no icon installed (optional)"

write_desktop "$INSTALL_DIR" "$EXE"

log "installed $APP_NAME${VERSION:+ v$VERSION} → $INSTALL_DIR"

if (( no_launch )); then
  log "done (--no-launch)."
  exit 0
fi

if (( auto )) || [[ -t 0 ]]; then
  log "launching…"
  ( cd "$INSTALL_DIR" && exec "./$EXE" ) &
  disown || true
fi
log "done."
exit 0
