#!/usr/bin/env bash
# Удалить клиент Steam из Wine-bottle(ов). Не трогает steam_api64.dll в папках GOG-игр.
set -euo pipefail
GAMES_DIR="$(cd "$(dirname "$0")" && pwd)"

purge_one_bottle() {
  local bottle_dir="$1" name="$2" wine64="$3" wine_lib="$4"
  echo ""
  echo "=== ${name} ==="

  pkill -9 -f "${bottle_dir}.*[Ss]team" 2>/dev/null || true
  pkill -9 -f "${bottle_dir}.*steam\.exe" 2>/dev/null || true

  export WINEPREFIX="${bottle_dir}"
  export DYLD_LIBRARY_PATH="${wine_lib}:${DYLD_LIBRARY_PATH:-}"
  local wineserver="${wine64%/wine64}/wineserver"
  [[ -x "${wineserver}" ]] && "${wineserver}" -k 2>/dev/null || true
  sleep 1

  local removed=0 d
  for d in \
    "${bottle_dir}/drive_c/Program Files (x86)/Steam" \
    "${bottle_dir}/drive_c/Program Files/Steam" \
    "${bottle_dir}/drive_c/Steam"; do
    if [[ -d "${d}" ]]; then
      echo "  rm -rf ${d}"
      rm -rf "${d}"
      removed=1
    fi
  done

  if [[ -x "${wine64}" ]]; then
    "${wine64}" reg delete 'HKCU\Software\Valve' /f >/dev/null 2>&1 || true
    "${wine64}" reg delete 'HKLM\Software\Valve' /f >/dev/null 2>&1 || true
  fi

  if [[ "${removed}" -eq 1 ]]; then
    echo "  OK: Steam client удалён"
  else
    echo "  OK: Steam client не найден"
  fi
}

purge_macos_steam() {
  echo ""
  echo "=== macOS Steam.app ==="
  local app
  for app in /Applications/Steam.app "${HOME}/Applications/Steam.app"; do
    if [[ -d "${app}" ]]; then
      echo "  rm -rf ${app}"
      rm -rf "${app}"
    fi
  done
  if [[ -d "${HOME}/Library/Application Support/Steam" ]]; then
    echo "  rm -rf ~/Library/Application Support/Steam"
    rm -rf "${HOME}/Library/Application Support/Steam"
  fi
  if ! [[ -d /Applications/Steam.app || -d "${HOME}/Applications/Steam.app" ]]; then
    echo "  Steam.app не установлен"
  fi
}

main() {
  echo "Удаление Steam (Wine + macOS), без steam_api64.dll в GOG Games/…"

  # GOG-Install
  if [[ -f "${GAMES_DIR}/gog/bottle.env" ]]; then
    # shellcheck source=gog/config.sh
    source "${GAMES_DIR}/gog/config.sh"
    purge_one_bottle "${BOTTLE_DIR}" "${BOTTLE_NAME}" "${WINE64}" "${WINE_LIB}"
  fi

  # HoMM / общий config
  # shellcheck source=config.sh
  source "${GAMES_DIR}/config.sh"
  purge_one_bottle "${BOTTLE_DIR}" "${BOTTLE_NAME}" "${WINE64}" "${WINE_LIB}"

  purge_macos_steam
  echo ""
  echo "Готово."
}

main "$@"
