#!/bin/bash
# Install DriftwoodXI Steam Deck helpers into ~/ffxi (or $DRIFTWOOD_ROOT).
set -euo pipefail

PKG="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${DRIFTWOOD_ROOT:-$HOME/ffxi}"
BIN="$ROOT/bin"

echo "==> DriftwoodXI Steam Deck package $(cat "$PKG/VERSION" 2>/dev/null || echo dev)"
echo "    Install root: $ROOT"

mkdir -p "$BIN" "$ROOT/art"
install -m 0755 "$PKG/scripts/env.sh" "$BIN/env.sh"
install -m 0755 "$PKG/scripts/play.sh" "$BIN/play.sh"
install -m 0755 "$PKG/scripts/play-steam.sh" "$BIN/play-steam.sh"
install -m 0755 "$PKG/scripts/padconfig.sh" "$BIN/padconfig.sh"

# Convenience symlinks at root (match earlier Deck layout)
ln -sfn bin/play.sh "$ROOT/play.sh"
ln -sfn bin/play-steam.sh "$ROOT/play-steam.sh"
ln -sfn bin/padconfig.sh "$ROOT/padconfig.sh"

if [ -d "$PKG/steam/art" ]; then
  cp -a "$PKG/steam/art/." "$ROOT/art/" 2>/dev/null || true
fi

# Desktop launcher
apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
mkdir -p "$apps"
cat > "$apps/driftwoodxi.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=DriftwoodXI
Comment=Final Fantasy XI — DriftwoodXI private server
Exec=$BIN/play.sh
Path=$ROOT
Icon=$ROOT/art/portrait.png
Terminal=false
Categories=Game;
StartupNotify=true
EOF
if [ -d "$HOME/Desktop" ]; then
  cp "$apps/driftwoodxi.desktop" "$HOME/Desktop/driftwoodxi.desktop"
  chmod +x "$HOME/Desktop/driftwoodxi.desktop" || true
fi

# Optional: add to Steam
if [ "${1:-}" = "--steam" ] || [ "${1:-}" = "-s" ]; then
  python3 "$PKG/steam/add-to-steam.py" --root "$ROOT" --art "$ROOT/art"
fi

cat <<EOF

Installed.
  Desktop:  $BIN/play.sh   (or DriftwoodXI icon)
  Steam:    $BIN/play-steam.sh
  Pad tool: $BIN/padconfig.sh

Prerequisites (you still need these):
  1. Updated FFXI client in a Wine/Proton prefix at: $ROOT/pfx
  2. Driftwood Ashita bundle at: $ROOT/Ashita
  3. GE-Proton11-5 under ~/.local/share/Steam/compatibilitytools.d/
  4. zenity + secret-tool (Desktop login / remember)

First run: Desktop Mode → DriftwoodXI → login → Remember.
Then: add to Steam with:  $PKG/install.sh --steam
      or: python3 $PKG/steam/add-to-steam.py

See README.md for full setup.
EOF
