#!/bin/bash

# omarchy:summary=Launch Steam, applying Asahi muvm login workarounds on Apple Silicon
# omarchy:group=launch
# omarchy:args=[--prepare|steam-args...]

set -euo pipefail

steam_root="$HOME/.local/share/Steam"

write_steam_desktop() {
  local app_dir="$HOME/.local/share/applications"
  # This is a user-owned override. Create it once without replacing existing
  # customizations, including a symlink managed by the user.
  [[ -e $app_dir/steam.desktop || -L $app_dir/steam.desktop ]] && return 0
  mkdir -p "$app_dir"
  cat >"$app_dir/steam.desktop" <<'EOF'
[Desktop Entry]
Name=Steam
Comment=Application for managing and playing games on Steam
Exec=omarchy-launch-steam %U
Icon=steam
Terminal=false
Type=Application
Categories=Network;FileTransfer;Game;
MimeType=x-scheme-handler/steam;x-scheme-handler/steamlink;
EOF
}

steam_client_ready() {
  [[ -d $steam_root/steamui ]] && compgen -G "$steam_root/*/steamui.so" >/dev/null
}

launch_fex_steam() {
  local launcher="$1"
  shift

  exec muvm -- FEXBash -c 'exec "$@"' omarchy-steam "$launcher" "$@"
}

patch_steam_ui() {
  local steamui="$steam_root/steamui"
  [[ -d $steamui ]] || return 0

  python3 - "$steamui" <<'PY'
import pathlib
import re
import sys

steamui = pathlib.Path(sys.argv[1])
pattern = re.compile(
    r"const t=\(0,(\w+)\.(\w+)\)\(\"System\.Network\.RegisterForDeviceChanges\"\);"
    r"t&&SteamClient\.System\.Network\.RegisterForDeviceChanges\(this\.OnNetworkDevicesChanged\),"
    r"\(0,\1\.\2\)\(\"System\.Network\.GetProxyInfo\"\)&&SteamClient\.System\.Network\.GetProxyInfo\(\)\.then\(e=>this\.m_proxyInfo=e\),"
    r"\(0,\1\.\2\)\(\"System\.Network\.RegisterForConnectivityTestChanges\"\)&&SteamClient\.System\.Network\.RegisterForConnectivityTestChanges\(this\.OnConnectivityTestStateChanged\),"
    r"t\|\|\(this\.m_bIsAwaitingInitialNetworkState=!1\)"
)
replacement = (
    r'const t=(0,\1.\2)("System.Network.RegisterForDeviceChanges")'
    r'&&!!(SteamClient.System&&SteamClient.System.Network&&"function"==typeof SteamClient.System.Network.RegisterForDeviceChanges);'
    r'try{t&&SteamClient.System.Network.RegisterForDeviceChanges(this.OnNetworkDevicesChanged)}catch(e){}'
    r'try{(0,\1.\2)("System.Network.GetProxyInfo")&&SteamClient.System.Network.GetProxyInfo().then(e=>this.m_proxyInfo=e)}catch(e){}'
    r'try{(0,\1.\2)("System.Network.RegisterForConnectivityTestChanges")&&SteamClient.System.Network.RegisterForConnectivityTestChanges(this.OnConnectivityTestStateChanged)}catch(e){}'
    r'this.m_bIsAwaitingInitialNetworkState=!1,this.m_bIsConnectedToANetwork=!0'
)

for path in sorted(steamui.glob("chunk~*.js")):
    text = path.read_text(errors="replace")
    # The exact original block no longer matches after replacement. A generic
    # connected-state assignment elsewhere in the chunk is not a patch marker.
    updated, count = pattern.subn(replacement, text, count=1)
    if count != 1:
        continue
    backup = path.with_suffix(path.suffix + ".omarchy-bak")
    if not backup.exists():
        backup.write_text(text)
    path.write_text(updated)
PY
}

prepare_asahi() {
  [[ $(uname -m) == aarch64 ]] || return 0
  write_steam_desktop
  patch_steam_ui
}

if [[ ${1:-} == --prepare ]]; then
  prepare_asahi
  exit 0
fi

if [[ $(uname -m) == aarch64 ]] && command -v muvm >/dev/null && command -v FEXBash >/dev/null; then
  launcher="$HOME/.local/share/fex-steam/steam-launcher/bin_steam.sh"

  if [[ -f $launcher ]]; then
    steam_args=(-cef-force-occlusion)
    if steam_client_ready; then
      # Steam's verifier replaces our patched UI chunk on every launch.
      # Keep update/bootstrap checks enabled while preserving that patch.
      steam_args+=(-noverifyfiles)
      prepare_asahi
    else
      write_steam_desktop
    fi

    launch_fex_steam "$launcher" "${steam_args[@]}" "$@"
  fi
fi

exec steam "$@"
