#!/bin/bash
# Installs the GreenHold Launcher for the current user: no root, no FUSE.
#   ./install-linux.sh [--feed ADDRESS_OR_FOLDER]
# Puts the program in ~/.local/share/GreenHold-Launcher, adds it to the application menu, puts a shortcut on the Desktop,
# and tells it where the update server is (default: ~/greenhold-feed when that folder exists).
# The game itself is downloaded by the launcher the first time it runs, into ~/.local/share/GreenHold.
#
# Double-clicking this file in a file manager works too: with no terminal around it opens one, so you can see what it does.
set -euo pipefail
SELF="$(readlink -f "$0")"
HERE="$(dirname "$SELF")"

# Started without a terminal (a double-click)? Run again inside one.
if [ ! -t 1 ] && [ -z "${GH_IN_TERMINAL:-}" ]; then
  export GH_IN_TERMINAL=1
  for t in konsole alacritty gnome-terminal kitty foot xterm; do
    command -v "$t" >/dev/null 2>&1 || continue
    case "$t" in
      gnome-terminal) exec gnome-terminal -- bash "$SELF" "$@" ;;
      kitty|foot)     exec "$t" bash "$SELF" "$@" ;;
      *)              exec "$t" -e bash "$SELF" "$@" ;;
    esac
  done
  export GH_NO_TERMINAL=1   # no terminal program found: finish quietly and report with a message box
fi

say() { printf '%s\n' "$*"; }
pause() { if [ -n "${GH_IN_TERMINAL:-}" ] && [ -z "${GH_NO_TERMINAL:-}" ]; then printf '\n'; read -r -p "$1" _ || true; fi; }
box() {   # a message box, for when there is no terminal to write in
  if command -v kdialog >/dev/null 2>&1; then kdialog --title "GreenHold Launcher" --msgbox "$1" 2>/dev/null || true
  elif command -v zenity >/dev/null 2>&1; then zenity --info --title "GreenHold Launcher" --text "$1" 2>/dev/null || true
  elif command -v notify-send >/dev/null 2>&1; then notify-send "GreenHold Launcher" "$1" || true; fi
}
on_exit() {
  local status=$?
  if [ $status -ne 0 ]; then
    say ""; say "Something went wrong (see the lines above). Nothing else was changed."
    pause "Press Enter to close this window... "
    [ -n "${GH_NO_TERMINAL:-}" ] && box "The installation did not finish. Run install-linux.sh from a terminal to see why."
  fi
}
trap on_exit EXIT

FEED=""
while [ $# -gt 0 ]; do
  case "$1" in
    --feed) FEED="$2"; shift 2 ;;
    *) say "usage: $0 [--feed ADDRESS_OR_FOLDER]"; exit 2 ;;
  esac
done
[ -z "$FEED" ] && [ -d "$HOME/greenhold-feed" ] && FEED="$HOME/greenhold-feed"

# the package sits next to this script (release/Linux/), or is found in the build folder (~/Builds/GreenHold-Tools/launcher/release/Linux/) when the script is run from the project
PKG="$(ls "$HERE"/GreenHold-Launcher-*-linux.tar.gz "${GREENHOLD_BUILD_DIR:-$HOME/Builds/GreenHold-Tools}"/launcher/release/Linux/GreenHold-Launcher-*-linux.tar.gz 2>/dev/null | sort -V | tail -1 || true)"
[ -n "$PKG" ] || { say "No Linux package found next to this script. Build one first: npm run dist:linux"; exit 1; }

DEST="$HOME/.local/share/GreenHold-Launcher"
APPS="$HOME/.local/share/applications"
say "== GreenHold Launcher installer =="
say "Installing $(basename "$PKG") to $DEST"
rm -rf "$DEST"; mkdir -p "$DEST" "$APPS"
tar -xzf "$PKG" -C "$DEST" --strip-components=1
cp "$DEST/resources/icon.png" "$DEST/icon.png"
chmod +x "$DEST/greenhold-launcher" "$DEST/resources/core/GreenHoldCore"

ENTRY="[Desktop Entry]
Type=Application
Name=GreenHold Launcher
Comment=Keeps GreenHold up to date and starts it
Exec=\"$DEST/greenhold-launcher\"
Icon=$DEST/icon.png
Terminal=false
Categories=Game;
StartupWMClass=GreenHold Launcher"
printf '%s\n' "$ENTRY" > "$APPS/greenhold-launcher.desktop"
DESKTOP_DIR="$(xdg-user-dir DESKTOP 2>/dev/null || echo "$HOME/Desktop")"
if [ -d "$DESKTOP_DIR" ]; then
  printf '%s\n' "$ENTRY" > "$DESKTOP_DIR/GreenHold Launcher.desktop"
  chmod +x "$DESKTOP_DIR/GreenHold Launcher.desktop"
  gio set "$DESKTOP_DIR/GreenHold Launcher.desktop" metadata::trusted true 2>/dev/null || true
  say "Desktop shortcut: $DESKTOP_DIR/GreenHold Launcher.desktop"
fi
command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" 2>/dev/null || true
say "Application menu entry added."

# where the update server is: written into the launcher's own settings (an existing settings file keeps its other values)
if [ -n "$FEED" ]; then
  CFG="${XDG_CONFIG_HOME:-$HOME/.config}/GreenHold Launcher"
  mkdir -p "$CFG"
  FEED="$FEED" CFG="$CFG" python3 - <<'PY'
import json, os
p = os.path.join(os.environ["CFG"], "settings.json")
try:
    d = json.load(open(p))
except Exception:
    d = {}
d["feedUrl"] = os.environ["FEED"]
json.dump(d, open(p, "w"), indent=2)
PY
  say "Update server: $FEED"
else
  say "No update server set: add \"feedUrl\" to ${XDG_CONFIG_HOME:-$HOME/.config}/GreenHold Launcher/settings.json"
fi

say ""
say "Done. GreenHold Launcher is installed."
say "Start it from the application menu or the Desktop shortcut \"GreenHold Launcher\"."
if [ -n "${GH_IN_TERMINAL:-}" ] && [ -z "${GH_NO_TERMINAL:-}" ]; then
  printf '\n'
  read -r -p "Start GreenHold Launcher now? [Y/n] " answer || answer="n"
  case "${answer:-y}" in
    [Nn]*) ;;
    *) setsid nohup "$DEST/greenhold-launcher" >/dev/null 2>&1 < /dev/null & say "Starting it..."; sleep 1 ;;
  esac
elif [ -n "${GH_NO_TERMINAL:-}" ]; then
  box "GreenHold Launcher is installed. Start it from the application menu or the Desktop shortcut."
fi
