#!/usr/bin/env bash
set -euo pipefail
CONTENTS_DIR="$(cd -- "$(dirname -- "$0")/.." && pwd)"
RESOURCES_DIR="$CONTENTS_DIR/Resources"
SUPPORT_DIR="${GOTHBOT_SUPPORT_DIR:-$HOME/Library/Application Support/GothBot}"
CONFIG="$SUPPORT_DIR/config"
VERSION_FILE="$RESOURCES_DIR/version"
INSTALLED_VERSION="$SUPPORT_DIR/installed-version"
LOG_DIR="$HOME/Library/Logs/GothBot"
mkdir -p -- "$LOG_DIR"

show_error() {
  local message="$1"
  /usr/bin/osascript -e 'on run argv' -e 'display dialog (item 1 of argv) with title "GothBot" buttons {"OK"} default button "OK" with icon stop' -e 'end run' "$message" >/dev/null 2>&1 || true
}
if [[ ! -f "$CONFIG" || ! -f "$INSTALLED_VERSION" || ! -f "$VERSION_FILE" || "$(cat "$INSTALLED_VERSION" 2>/dev/null)" != "$(cat "$VERSION_FILE" 2>/dev/null)" ]]; then
  if [[ "${GOTHBOT_FOREGROUND_SETUP:-0}" == 1 ]]; then exec /bin/bash "$RESOURCES_DIR/setup.sh" --launch; fi
  setup_command="$(printf '%q ' /bin/bash "$RESOURCES_DIR/setup.sh" --launch)"
  /usr/bin/osascript -e 'on run argv' -e 'tell application "Terminal"' -e 'activate' -e 'do script (item 1 of argv)' -e 'end tell' -e 'end run' "$setup_command" >/dev/null
  exit 0
fi

# The config is generated by setup.sh with shell-escaped values and is private to this user.
# shellcheck source=/dev/null
source "$CONFIG"
if [[ ! -x "${GOTHBOT_WINE:-}" || ! -f "$GOTHBOT_GAME_DIR/StrongholdKingdoms.exe" ]]; then
  rm -f -- "$CONFIG"
  show_error 'GothBot needs to repair its Wine environment. Open the application again to start setup.'
  exit 1
fi
export WINEPREFIX
cd -- "$GOTHBOT_GAME_DIR"
"$GOTHBOT_WINE" StrongholdKingdoms.exe >>"$LOG_DIR/launcher.log" 2>&1 || {
  result=$?
  show_error "GothBot stopped with exit code $result. See $LOG_DIR/launcher.log for details."
  exit "$result"
}
