#!/usr/bin/env bash
# Общие kill/lock для GOG Galaxy в GOG-bottle.
GOG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

WINE_SERV="${WHISKY_LIBS}/Libraries/Wine/bin/wineserver"

gog_lock_files_dir() {
  echo "${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/lock-files"
}

gog_remove_lock_files() {
  local d
  d="$(gog_lock_files_dir)"
  [[ -d "${d}" ]] || return 0
  rm -f "${d}"/*.lock 2>/dev/null || true
}

gog_kill_all() {
  pkill -9 -f 'explorer.exe /desktop=GOGGalaxy' 2>/dev/null || true
  pkill -9 -f 'explorer /desktop=GOGGalaxy' 2>/dev/null || true
  pkill -9 -f 'GalaxyClient Helper' 2>/dev/null || true
  pkill -9 -f 'GalaxyClient' 2>/dev/null || true
  pkill -9 -f 'GalaxyUpdater' 2>/dev/null || true
  pkill -9 -f 'GalaxyInstaller' 2>/dev/null || true
  pkill -9 -f 'GalaxySetup' 2>/dev/null || true
  pkill -9 -f 'GalaxyWebInstaller' 2>/dev/null || true
  pkill -9 -f 'GOG_Galaxy_' 2>/dev/null || true
  pkill -9 -f 'GOG Galaxy' 2>/dev/null || true
  pkill -9 -f "${BOTTLE_ID}.*[Ss]team" 2>/dev/null || true
  pkill -9 -f "${BOTTLE_DIR}.*steam\.exe" 2>/dev/null || true
  pkill -9 -f "${BOTTLE_ID}.*wine" 2>/dev/null || true
  pkill -9 -f 'winedevice\.exe' 2>/dev/null || true
  pkill -9 -f 'wine64-preloader' 2>/dev/null || true
  pkill -9 -f 'wine64\.exe' 2>/dev/null || true
  sleep 1
  if [[ -d "${BOTTLE_DIR}" ]]; then
    export WINEPREFIX="${BOTTLE_DIR}"
    [[ -x "${WINE_SERV}" ]] && "${WINE_SERV}" -k 2>/dev/null || true
    sleep 1
    gog_remove_lock_files
  fi
  sleep 1
}

gog_galaxy_running() {
  pgrep -f 'GalaxyClient\.exe' >/dev/null 2>&1 \
    || pgrep -f 'GalaxyClient Helper' >/dev/null 2>&1
}

gog_wait_log_line() {
  local log="$1" pattern="$2" timeout="${3:-30}"
  local i
  for i in $(seq 1 "${timeout}"); do
    [[ -f "${log}" ]] && grep -q "${pattern}" "${log}" 2>/dev/null && return 0
    sleep 1
  done
  return 1
}

gog_mac_activate_wine() {
  osascript -e '
tell application "System Events"
  repeat with proc in (every process whose name contains "wine" or name contains "Wine")
    try
      set frontmost of proc to true
      exit repeat
    end try
  end repeat
end tell' 2>/dev/null || true
}
