#!/bin/bash
# Combat Arms Classic — installazione su ChromeOS (ambiente Linux / Crostini, Chromebook x86_64).
# Il client Windows gira con Wine (WineHQ) in un prefix dedicato.
# Uso, nel Terminale Linux del Chromebook:
#   bash install-chromeos.sh [percorso/CombatArmsClassic-Windows10-11-x64.exe]
# Senza argomento cerca il setup nella cartella Download condivisa con Linux.
set -euo pipefail

APP_NAME="Combat Arms Classic"
DATA="$HOME/.local/share/CombatArmsClassic"
PREFIX="$DATA/wineprefix"
DOWNLOAD_PAGE="https://combatarms.world/downloads#chromeos"
ACCOUNT_PAGE="https://combatarms.world/account?tab=account#pl-client-title"

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

# Prefer the modern Windows package, including browser-renamed duplicates.
# Keep old generic setup names as fallbacks; the dedicated legacy package is not for these platforms.
# Partial downloads are ignored. A filename alone does not establish authenticity.
find_setup() {
  local pattern dir f best=""
  for pattern in 'CombatArmsClassic-Windows10-11-x64*.exe' 'CombatArmsClassicSetup*.exe' '*'; do
    for dir in "$@"; do
      [ -d "$dir" ] || continue
      while IFS= read -r -d '' f; do
        if [ -z "$best" ] || [ "$f" -nt "$best" ]; then best="$f"; fi
      done < <(find "$dir" -maxdepth 1 -type f -iname "$pattern"         \( -iname 'CombatArms*Setup*.exe' -o -iname '*combat*arms*.exe' -o -iname '*setup*.exe' \)         ! -iname 'CombatArmsClassic-Windows7-8.1-x64*.exe'         ! -iname 'MicrosoftEdge*' -size +10M -print0 2>/dev/null)
      [ -n "$best" ] && { printf '%s\n' "$best"; return 0; }
    done
  done
  return 1
}
ask_setup() {
  # Drag-and-drop into Terminal pastes a quoted or backslash-escaped path.
  local answer
  [ -t 0 ] || return 1
  printf '\nDrag the official Windows 10/11 setup into this window and press Enter (or just Enter to quit): ' >&2
  IFS= read -r answer || return 1
  answer="${answer%"${answer##*[![:space:]]}"}"; answer="${answer#\'}"; answer="${answer%\'}"; answer="${answer#\"}"; answer="${answer%\"}"
  [ -f "$answer" ] || answer=$(printf '%s' "$answer" | sed 's/\\\(.\)/\1/g')
  [ -f "$answer" ] && printf '%s\n' "$answer"
}

# --- Requisiti ---------------------------------------------------------------
[ "$(uname -s)" = "Linux" ] || die "Esegui lo script nel Terminale Linux di ChromeOS."
ARCH=$(uname -m)
[ "$ARCH" = "x86_64" ] || die "Chromebook $ARCH non supportato: il client e x86 e serve un Chromebook Intel/AMD (x86_64)."
if [ ! -d /opt/google/cros-containers ]; then
  echo "Avviso: non sembra il container Linux di ChromeOS; procedo come Linux generico."
fi
if [ ! -e /dev/dri/renderD128 ]; then
  echo "Avviso: accelerazione GPU non attiva nel container Linux."
  echo "        Attivala in chrome://flags/#crostini-gpu-support e riavvia Linux, altrimenti il gioco sara molto lento."
fi
FREE_GB=$(df -BG --output=avail "$HOME" | tail -1 | tr -dc '0-9')
[ "${FREE_GB:-0}" -ge 16 ] || die "Spazio libero insufficiente nel disco Linux (${FREE_GB} GB). Servono almeno 16 GB: aumentalo da Impostazioni > Sviluppatori > Ambiente di sviluppo Linux."

# --- Setup del client ------------------------------------------------------------
SETUP="${1:-}"
[ -n "$SETUP" ] && [ ! -f "$SETUP" ] && die "Setup file not found: $SETUP"
[ -z "$SETUP" ] && SETUP=$(find_setup /mnt/chromeos/MyFiles/Downloads "$HOME/Downloads" "$HOME" || true)
if [ -z "$SETUP" ]; then
  echo
  echo "CombatArmsClassic-Windows10-11-x64.exe was not found in your Downloads folder (older generic setup names are also supported)."
  echo "The setup is personal: sign in on the website and open Account > Download the client > Windows 10/11."
  command -v garcon-url-handler >/dev/null 2>&1 && garcon-url-handler "$ACCOUNT_PAGE" >/dev/null 2>&1 || true
  SETUP=$(ask_setup || true)
fi
[ -n "$SETUP" ] && [ -f "$SETUP" ] || die "Download CombatArmsClassic-Windows10-11-x64.exe from your account (Account > Download the client > Windows 10/11) at https://combatarms.world/account, share the Downloads folder with Linux (right-click > Share with Linux) and run this installer again. Guide: $DOWNLOAD_PAGE"
case "$(printf '%s' "${SETUP##*/}" | tr '[:upper:]' '[:lower:]')" in
  combatarmsclassic-windows7-8.1-x64*.exe) die "This is the Windows 7/8.1 package. Download the Windows 10/11 package for macOS or ChromeOS." ;;
esac
say "Setup: $SETUP"

# --- Wine (WineHQ stable) -----------------------------------------------------------
. /etc/os-release
CODENAME="${VERSION_CODENAME:-bookworm}"
if ! command -v wine >/dev/null 2>&1 || ! wine --version 2>/dev/null | grep -qE 'wine-(9|[1-9][0-9])\.'; then
  say "Installo Wine da WineHQ ($ID $CODENAME) — serve la password sudo se richiesta"
  sudo dpkg --add-architecture i386
  sudo apt-get update
  sudo apt-get install -y --no-install-recommends ca-certificates wget gnupg
  sudo mkdir -pm755 /etc/apt/keyrings
  sudo wget -qO /etc/apt/keyrings/winehq-archive.key https://dl.winehq.org/wine-builds/winehq.key
  case "$ID" in
    debian|ubuntu) REPO_ID="$ID" ;;
    *) REPO_ID="debian" ;;
  esac
  sudo wget -qNP /etc/apt/sources.list.d/ "https://dl.winehq.org/wine-builds/$REPO_ID/dists/$CODENAME/winehq-$CODENAME.sources" \
    || die "WineHQ non pubblica pacchetti per $REPO_ID $CODENAME. Aggiorna il container Linux (Debian 12 o successivo)."
  sudo apt-get update
  sudo apt-get install -y --install-recommends winehq-stable
fi
sudo apt-get install -y --no-install-recommends winbind cabextract icoutils xdg-utils >/dev/null 2>&1 || true
command -v winetricks >/dev/null 2>&1 || {
  mkdir -p "$DATA/bin"
  wget -qO "$DATA/bin/winetricks" https://raw.githubusercontent.com/Winetricks/winetricks/20250102/src/winetricks && chmod +x "$DATA/bin/winetricks" || true
  export PATH="$DATA/bin:$PATH"
}
say "Wine: $(wine --version)"

# --- Prefix -----------------------------------------------------------------------
mkdir -p "$PREFIX"
export WINEPREFIX="$PREFIX" WINEARCH=win64 WINEDEBUG=-all
wineboot -i >/dev/null 2>&1 || true
wine reg add 'HKCU\Software\Wine' /v Version /d win10 /f >/dev/null 2>&1 || true
# Il mouse resta catturato nella finestra del gioco (mira FPS).
wine reg add 'HKCU\Software\Wine\X11 Driver' /v GrabFullscreen /d Y /f >/dev/null 2>&1 || true
wine reg add 'HKCU\Software\Wine\DirectInput' /v MouseWarpOverride /d force /f >/dev/null 2>&1 || true

if command -v winetricks >/dev/null 2>&1; then
  say "Preparo WebView2 con winetricks (puo richiedere qualche minuto)"
  winetricks -q webview2 || echo "winetricks webview2 non riuscito: ci prova il setup."
fi

say "Installo il gioco (setup silenzioso, ~7 GB)"
wine "$SETUP" /S || die "Il setup non e terminato correttamente (vedi setup-verification.log nella cartella del gioco nel prefix)."

LOCALAPPDATA_WIN=$(wine cmd /c 'echo %LOCALAPPDATA%' 2>/dev/null | tr -d '\r' | tail -1)
LAUNCHER_WIN="$LOCALAPPDATA_WIN\\Programs\\CombatArmsClassic\\Launcher\\CombatArmsClassicLauncher.exe"
LAUNCHER_UNIX=$(winepath -u "$LAUNCHER_WIN" 2>/dev/null | tr -d '\r' | tail -1)
[ -f "$LAUNCHER_UNIX" ] || die "Launcher non trovato dopo l'installazione ($LAUNCHER_WIN)."

# --- Avvio, icona e voce nel launcher di ChromeOS ---------------------------------
RUN="$DATA/run.sh"
cat > "$RUN" <<EOF
#!/bin/bash
# Avvia il launcher Windows nel prefix dedicato. Argomento opzionale: link nepix-ca://
export WINEPREFIX="$PREFIX" WINEDEBUG=-all
cd "\$(dirname "$LAUNCHER_UNIX")"
exec wine "$LAUNCHER_WIN" "\$@"
EOF
chmod +x "$RUN"

ICON="$DATA/combat-arms-classic.png"
cp "$(dirname "$LAUNCHER_UNIX")/ui/assets/combat-arms-classic.png" "$ICON" 2>/dev/null || ICON="wine"

mkdir -p "$HOME/.local/share/applications"
DESKTOP="$HOME/.local/share/applications/combat-arms-classic.desktop"
cat > "$DESKTOP" <<EOF
[Desktop Entry]
Type=Application
Name=$APP_NAME
Comment=Combat Arms Classic (Nepix Network)
Exec="$RUN" %u
Icon=$ICON
Terminal=false
Categories=Game;
MimeType=x-scheme-handler/nepix-ca;
StartupWMClass=combatarmsclassiclauncher.exe
EOF
xdg-mime default combat-arms-classic.desktop x-scheme-handler/nepix-ca 2>/dev/null || true
update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true

say "Diagnostica piattaforma"
REPORT_UNIX="$DATA/platform-info.json"
wine "$LAUNCHER_WIN" --platform-info "$(winepath -w "$REPORT_UNIX" | tr -d '\r')" >/dev/null 2>&1 || true
[ -f "$REPORT_UNIX" ] && cat "$REPORT_UNIX" && echo
wine "$LAUNCHER_WIN" --check-runtime >/dev/null 2>&1 && echo "WebView2: OK" || echo "WebView2 non disponibile: il launcher aprira la sua interfaccia nel browser di sistema."

say "Fatto. Trovi \"$APP_NAME\" nel launcher di ChromeOS, cartella App Linux."
echo "Consiglio: usa la modalita finestra e una risoluzione 1280x720 sui Chromebook meno potenti."
