#!/bin/bash
# Combat Arms Classic — installazione su macOS (Apple Silicon M1+ o Intel).
# Il client resta quello Windows: gira in un prefix Wine dedicato (CrossOver consigliato,
# in alternativa un Wine gia installato). Uso:
#   ./install-macos.command [percorso/CombatArmsClassic-Windows10-11-x64.exe]
# Senza argomento cerca il setup in ~/Downloads.
set -euo pipefail

APP_NAME="Combat Arms Classic"
BOTTLE="CombatArmsClassic"
SUPPORT="$HOME/Library/Application Support/CombatArmsClassic"
PREFIX="$SUPPORT/wineprefix"
APP_BUNDLE="$HOME/Applications/$APP_NAME.app"
DOWNLOAD_PAGE="https://combatarms.world/downloads#macos"
ACCOUNT_PAGE="https://combatarms.world/account?tab=account#pl-client-title"
CROSSOVER="/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin"

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"
}

[ "$(uname -s)" = "Darwin" ] || die "Questo script e per macOS."
MACOS_MAJOR=$(sw_vers -productVersion | cut -d. -f1)
[ "$MACOS_MAJOR" -ge 13 ] || die "Serve macOS 13 Ventura o successivo."

if [ "$(uname -m)" = "arm64" ]; then
  if ! /usr/bin/pgrep -q oahd; then
    say "Installo Rosetta 2 (necessaria per eseguire il client x86 su Apple Silicon)"
    /usr/sbin/softwareupdate --install-rosetta --agree-to-license || die "Rosetta 2 non installata."
  fi
fi

# --- Setup del client -------------------------------------------------------
SETUP="${1:-}"
[ -n "$SETUP" ] && [ ! -f "$SETUP" ] && die "Setup file not found: $SETUP"
[ -z "$SETUP" ] && SETUP=$(find_setup "$HOME/Downloads" "$HOME/Desktop" || 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."
  open "$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, then 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"

# --- Motore Wine -----------------------------------------------------------
MODE=""
if [ -x "$CROSSOVER/wine" ]; then
  MODE="crossover"
elif [ -n "${WINE:-}" ] && command -v "$WINE" >/dev/null 2>&1; then
  MODE="wine"
elif command -v wine >/dev/null 2>&1; then
  WINE=$(command -v wine); MODE="wine"
elif [ -x "/Applications/Wine Stable.app/Contents/Resources/wine/bin/wine" ]; then
  WINE="/Applications/Wine Stable.app/Contents/Resources/wine/bin/wine"; MODE="wine"
elif command -v brew >/dev/null 2>&1; then
  say "Nessun Wine trovato: provo Homebrew (tap gcenx/wine)"
  brew tap gcenx/wine && brew install --cask wine-crossover || true
  if command -v wine >/dev/null 2>&1; then WINE=$(command -v wine); MODE="wine"; fi
fi
[ -n "$MODE" ] || die "Installa CrossOver (https://www.codeweavers.com/crossover) oppure Wine, poi rilancia lo script."

if [ "$MODE" = "crossover" ]; then
  say "Uso CrossOver (bottle \"$BOTTLE\")"
  if ! "$CROSSOVER/cxbottle" --bottle "$BOTTLE" --status >/dev/null 2>&1; then
    "$CROSSOVER/cxbottle" --create --bottle "$BOTTLE" --template win10_64 --description "$APP_NAME" || die "Creazione bottle non riuscita."
  fi
  run_wine() { "$CROSSOVER/wine" --bottle "$BOTTLE" "$@"; }
  WINE_CMD="\"$CROSSOVER/wine\" --bottle \"$BOTTLE\""
else
  say "Uso Wine: $WINE ($("$WINE" --version 2>/dev/null || echo versione sconosciuta))"
  mkdir -p "$PREFIX"
  export WINEPREFIX="$PREFIX" WINEARCH=win64 WINEDEBUG=-all
  run_wine() { WINEPREFIX="$PREFIX" WINEDEBUG=-all "$WINE" "$@"; }
  WINE_CMD="WINEPREFIX=\"$PREFIX\" WINEDEBUG=-all \"$WINE\""
  run_wine wineboot -i >/dev/null 2>&1 || true
fi

say "Configuro il prefix (Windows 10, tasti Option/Command per il gioco)"
run_wine reg add 'HKCU\Software\Wine' /v Version /d win10 /f >/dev/null 2>&1 || true
run_wine reg add 'HKCU\Software\Wine\Mac Driver' /v LeftOptionIsAlt /d Y /f >/dev/null 2>&1 || true
run_wine reg add 'HKCU\Software\Wine\Mac Driver' /v RightOptionIsAlt /d Y /f >/dev/null 2>&1 || true
run_wine reg add 'HKCU\Software\Wine\Mac Driver' /v LeftCommandIsCtrl /d Y /f >/dev/null 2>&1 || true
# Launcher UI in the Mac browser: under CrossOver/Wine WebView2 runs but its window stays white.
run_wine reg add 'HKCU\Environment' /v NEPIX_BROWSER_UI /d 1 /f >/dev/null 2>&1 || true

# WebView2 (UI del launcher): il setup lo installa da solo; winetricks e il ripiego se presente.
if command -v winetricks >/dev/null 2>&1 && [ "$MODE" = "wine" ]; then
  say "Preparo WebView2 con winetricks (puo richiedere qualche minuto)"
  WINEPREFIX="$PREFIX" winetricks -q webview2 || echo "winetricks webview2 non riuscito: ci prova il setup."
fi

say "Installo il gioco (setup silenzioso, ~7 GB)"
run_wine "$SETUP" /S || die "Il setup non e terminato correttamente. Log: %LOCALAPPDATA%\\Programs\\CombatArmsClassic\\setup-verification.log nel prefix."

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

# --- Script di avvio + app con gestione link nepix-ca:// -----------------------
mkdir -p "$SUPPORT"
RUN="$SUPPORT/run.sh"
cat > "$RUN" <<EOF
#!/bin/bash
# Avvia il launcher Windows nel prefix dedicato. Argomento opzionale: link nepix-ca://
cd "\$(dirname "$LAUNCHER_UNIX")"
export NEPIX_BROWSER_UI=1
exec $WINE_CMD "$LAUNCHER_WIN" "\$@"
EOF
chmod +x "$RUN"

say "Creo $APP_BUNDLE"
mkdir -p "$HOME/Applications"
rm -rf "$APP_BUNDLE"
APPLESCRIPT=$(mktemp -t ca-applet).applescript
cat > "$APPLESCRIPT" <<EOF
on run
	do shell script quoted form of "$RUN" & " > /dev/null 2>&1 &"
end run
on open location theURL
	do shell script quoted form of "$RUN" & " " & quoted form of theURL & " > /dev/null 2>&1 &"
end open location
EOF
osacompile -o "$APP_BUNDLE" "$APPLESCRIPT"
rm -f "$APPLESCRIPT"
PLIST="$APP_BUNDLE/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleName $APP_NAME" "$PLIST" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :CFBundleIdentifier string world.combatarms.classic" "$PLIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier world.combatarms.classic" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes array" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes:0 dict" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes:0:CFBundleURLName string Combat Arms Nexus" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string nepix-ca" "$PLIST"
ICON_PNG="$(dirname "$LAUNCHER_UNIX")/ui/assets/combat-arms-classic.png"
if [ -f "$ICON_PNG" ]; then
  ICONSET=$(mktemp -d)/app.iconset; mkdir -p "$ICONSET"
  for s in 16 32 128 256 512; do
    sips -z $s $s "$ICON_PNG" --out "$ICONSET/icon_${s}x${s}.png" >/dev/null 2>&1 || true
    sips -z $((s*2)) $((s*2)) "$ICON_PNG" --out "$ICONSET/icon_${s}x${s}@2x.png" >/dev/null 2>&1 || true
  done
  iconutil -c icns "$ICONSET" -o "$APP_BUNDLE/Contents/Resources/applet.icns" 2>/dev/null || true
fi
codesign --force --deep --sign - "$APP_BUNDLE" >/dev/null 2>&1 || true
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$APP_BUNDLE" || true

say "Diagnostica piattaforma"
REPORT_UNIX="$SUPPORT/platform-info.json"
REPORT_WIN=$(run_wine winepath -w "$REPORT_UNIX" 2>/dev/null | tr -d '\r' | tail -1)
run_wine "$LAUNCHER_WIN" --platform-info "$REPORT_WIN" >/dev/null 2>&1 || true
[ -f "$REPORT_UNIX" ] && cat "$REPORT_UNIX" && echo
echo "The launcher opens its interface in your Mac browser (Safari/Chrome); keep the small launcher window open while you play."

say "Fatto. Apri \"$APP_NAME\" da Applicazioni/Launchpad."
echo "Consiglio: nel launcher lascia attiva la modalita finestra al primo avvio."
