#!/usr/bin/env bash
# Installs the zy games launcher for this user: ~/.local/share/zy, plus an app-menu entry. Run: bash zy-install.sh
set -euo pipefail
D="${XDG_DATA_HOME:-$HOME/.local/share}/zy"
mkdir -p "$D" "$HOME/.local/share/applications"
echo "zy: downloading the launcher..."
tmp=$(mktemp -d)
curl -fL --progress-bar "https://download.kingtalgo.com/zy/zy-24-linux.tar.gz" -o "$tmp/zy.tar.gz"  # number set by ship_zy.sh
rm -rf "$D/app.new" && mkdir -p "$D/app.new" && tar -xzf "$tmp/zy.tar.gz" -C "$D/app.new" && rm -rf "$tmp"
# The wrapper swaps in a staged update (app.new) before starting, so the launcher never overwrites itself while running.
cat > "$D/zy" <<'WRAP'
#!/bin/sh
D="${XDG_DATA_HOME:-$HOME/.local/share}/zy"
if [ -d "$D/app.new" ]; then rm -rf "$D/app.old"; [ -d "$D/app" ] && mv "$D/app" "$D/app.old"; mv "$D/app.new" "$D/app"; rm -rf "$D/app.old"; fi
exec "$D/app/zy" "$@"
WRAP
chmod +x "$D/zy"
printf '[Desktop Entry]\nType=Application\nName=zy\nComment=Games launcher\nExec=%s\nTerminal=false\nCategories=Game;\n' "$D/zy" \
  > "$HOME/.local/share/applications/zy.desktop"
# Also a command on PATH: sway's default Meta+D menu (dmenu) lists PATH programs, not .desktop entries.
mkdir -p "$HOME/.local/bin" && ln -sf "$D/zy" "$HOME/.local/bin/zy"
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) echo "zy: note: ~/.local/bin is not on your PATH, so menus like dmenu won't list zy until it is.";; esac
echo "zy: installed. Start it from your app menu (\"zy\") or run $D/zy"
nohup "$D/zy" >/dev/null 2>&1 &
