#!/usr/bin/env bash
set -euo pipefail

server_host="${EQ_SERVER_HOST:-192.168.0.252}"
server_port="${EQ_SERVER_PORT:-5998}"
client_source="${1:-${EQ_CLIENT_SOURCE:-}}"
install_root="${EQ_INSTALL_ROOT:-${HOME}/Games/everquest-legends-proton}"
client_target="${install_root}/pfx/drive_c/users/Public/Daybreak Game Company/Installed Games/EverQuest Legends"
launcher="${HOME}/.local/bin/eqlegends"

if [[ -z "${client_source}" ]]; then
  for candidate in \
    "${HOME}/Games/EverQuest Legends" \
    "${HOME}/Games/everquest-legends" \
    "${HOME}/Games/everquest-legends-proton/pfx/drive_c/users/Public/Daybreak Game Company/Installed Games/EverQuest Legends"; do
    if [[ -f "${candidate}/eqgame.exe" ]]; then
      client_source="${candidate}"
      break
    fi
  done
fi

if [[ -z "${client_source}" ]]; then
  printf 'No EverQuest Legends client was found.\n' >&2
  printf 'Place your own client under: %s\n' "${HOME}/Games/EverQuest Legends" >&2
  printf 'Or rerun with EQ_CLIENT_SOURCE=/path/to/your/client.\n' >&2
  exit 2
fi

if [[ ! -f "${client_source}/eqgame.exe" ]]; then
  printf 'Missing eqgame.exe under: %s\n' "${client_source}" >&2
  exit 2
fi

proton_bin="${EQ_PROTON_BIN:-}"
if [[ -z "${proton_bin}" ]]; then
  for candidate in \
    "${HOME}"/.steam/root/compatibilitytools.d/GE-Proton*/proton \
    "${HOME}"/.steam/steam/compatibilitytools.d/GE-Proton*/proton; do
    if [[ -x "${candidate}" ]]; then
      proton_bin="${candidate}"
    fi
  done
fi

if [[ -z "${proton_bin}" || ! -x "${proton_bin}" ]]; then
  printf 'GE-Proton is required for the EverQuest Legends launcher.\n' >&2
  printf 'Install GE-Proton in Steam compatibilitytools.d or set EQ_PROTON_BIN.\n' >&2
  exit 3
fi

mkdir -p "${client_target}" "${install_root}/pfx" "$(dirname "${launcher}")"

if [[ "$(readlink -f "${client_source}")" != "$(readlink -f "${client_target}")" ]]; then
  printf 'Installing the user-supplied EverQuest Legends client into %s ...\n' "${client_target}"
  cp -a "${client_source}/." "${client_target}/"
else
  printf 'Using the existing EverQuest Legends client at %s ...\n' "${client_target}"
fi

cat > "${client_target}/eqhost.txt" <<EOF
[LoginServer]
Host=${server_host}:${server_port}
EOF

STEAM_COMPAT_DATA_PATH="${install_root}/pfx" \
STEAM_COMPAT_CLIENT_INSTALL_PATH="${HOME}/.steam/root" \
  "${proton_bin}" run wineboot -u >/dev/null

printf '#!/usr/bin/env bash\nset -euo pipefail\nexport STEAM_COMPAT_DATA_PATH=%q\nexport STEAM_COMPAT_CLIENT_INSTALL_PATH=%q\ncd %q\nexec %q run eqgame.exe patchme\n' \
  "${install_root}/pfx" "${HOME}/.steam/root" "${client_target}" "${proton_bin}" > "${launcher}"
chmod 0755 "${launcher}"

printf '\nEQ Legends is ready. Launch it with:\n  %s\n' "${launcher}"
printf 'Login endpoint: %s:%s (reachable from the Polyhydra LAN)\n' "${server_host}" "${server_port}"
