#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# drAIML WebGPU installer (Linux, macOS). WebGPU is part of the browser; nothing is downloaded. This switches it on
# where the browser ships it turned off, exactly as you would by hand in chrome://flags or about:config:
#
#   Chrome, Chromium, Brave, Edge, Vivaldi, Opera:  #enable-unsafe-webgpu, #enable-vulkan (Linux), #ignore-gpu-blocklist (--blocklist)
#                                                   written to each browser's "Local State" (where chrome://flags keeps them)
#   Firefox (--firefox):                            user_pref("dom.webgpu.enabled", true) in each profile's user.js
#
# Close the browser first: a running browser rewrites its settings on exit and would undo the change.
#
#   bash webgpu-enable.sh                 # Chromium-family browsers
#   bash webgpu-enable.sh --firefox       # also Firefox
#   bash webgpu-enable.sh --blocklist     # also ignore the GPU blocklist (only if the card is blocklisted)
#   bash webgpu-enable.sh --dry-run       # show what would change
#   bash webgpu-enable.sh --undo          # remove exactly what this script added
#   bash webgpu-enable.sh --dir PATH      # one browser user-data directory (or Firefox profile) only
set -euo pipefail

FIREFOX=0 BLOCKLIST=0 DRY=0 UNDO=0 ONLY=""
while [ $# -gt 0 ]; do
  case "$1" in
    --firefox) FIREFOX=1 ;; --blocklist) BLOCKLIST=1 ;; --dry-run) DRY=1 ;; --undo) UNDO=1 ;;
    --dir) ONLY="$2"; shift ;;
    -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
    *) echo "unknown option: $1 (see --help)" >&2; exit 2 ;;
  esac
  shift
done
command -v python3 >/dev/null || { echo "needs python3 (to edit the browser's JSON settings safely)" >&2; exit 1; }

OS=$(uname -s)
FLAGS=("enable-unsafe-webgpu")
[ "$OS" = Linux ] && FLAGS+=("enable-vulkan@1")
[ "$BLOCKLIST" = 1 ] && FLAGS+=("ignore-gpu-blocklist")

if [ "$OS" = Darwin ]; then
  A="$HOME/Library/Application Support"
  CHROMIUM_DIRS=("$A/Google/Chrome" "$A/Google/Chrome Beta" "$A/Chromium" "$A/BraveSoftware/Brave-Browser" "$A/Microsoft Edge"
                 "$A/Vivaldi" "$A/com.operasoftware.Opera")
  FIREFOX_ROOTS=("$A/Firefox/Profiles")
else
  C="$HOME/.config" F="$HOME/.var/app"
  CHROMIUM_DIRS=("$C/google-chrome" "$C/google-chrome-beta" "$C/google-chrome-unstable" "$C/chromium" "$HOME/snap/chromium/common/chromium"
                 "$C/BraveSoftware/Brave-Browser" "$C/BraveSoftware/Brave-Browser-Beta" "$C/microsoft-edge" "$C/vivaldi" "$C/opera"
                 "$F/com.google.Chrome/config/google-chrome" "$F/org.chromium.Chromium/config/chromium"
                 "$F/com.brave.Browser/config/BraveSoftware/Brave-Browser" "$F/com.microsoft.Edge/config/microsoft-edge")
  FIREFOX_ROOTS=("$HOME/.mozilla/firefox" "$HOME/snap/firefox/common/.mozilla/firefox" "$F/org.mozilla.firefox/.mozilla/firefox")
fi

# a browser holds a lock while it runs: Chromium's SingletonLock symlink (host-pid), Firefox's "lock" symlink
running() {
  local lock="$1" target pid
  [ -L "$lock" ] || return 1
  target=$(readlink "$lock"); pid=$(printf '%s' "$target" | sed 's/.*[^0-9]//')   # Chromium host-PID, Firefox IP:+PID
  [[ "$pid" =~ ^[0-9]+$ ]] || return 0                 # a lock we cannot read: treat as running
  kill -0 "$pid" 2>/dev/null
}

# a Flatpak browser's lock names a PID inside its sandbox, so ask flatpak which apps are running
flatpak_running() {
  local app
  case "$1" in "$HOME/.var/app/"*) app=${1#"$HOME/.var/app/"}; app=${app%%/*} ;; *) return 1 ;; esac
  command -v flatpak >/dev/null && flatpak ps --columns=application 2>/dev/null | grep -qx "$app"
}

changed=0 skipped=0
chromium() {
  local dir="$1" state="$1/Local State"
  [ -f "$state" ] || return 0
  if running "$dir/SingletonLock" || flatpak_running "$dir"; then echo "• $dir — browser is running: close it and run this again"; skipped=$((skipped+1)); return 0; fi
  local out
  out=$(python3 - "$state" "$UNDO" "$DRY" "${FLAGS[@]}" <<'PY'
import json, os, shutil, sys, time
state, undo, dry, flags = sys.argv[1], sys.argv[2] == "1", sys.argv[3] == "1", sys.argv[4:]
side = state + ".webgpu-helper.json"            # which entries this script added, so --undo removes only those
with open(state, encoding="utf-8") as f: d = json.load(f)
labs = d.setdefault("browser", {}).setdefault("enabled_labs_experiments", [])
if undo:
    mine = json.load(open(side)).get("added", []) if os.path.exists(side) else []
    new = [x for x in labs if x not in mine]
    what = [x for x in labs if x in mine]
else:
    names = {x.split("@")[0] for x in labs}
    what = [x for x in flags if x.split("@")[0] not in names]
    new = labs + what
if not what: print("unchanged"); sys.exit(0)
print(("would " if dry else "") + ("remove " if undo else "add ") + " ".join(what))
if dry: sys.exit(0)
shutil.copy2(state, f"{state}.bak-webgpu-{time.strftime('%Y%m%d-%H%M%S')}")
d["browser"]["enabled_labs_experiments"] = new
tmp = state + ".tmp-webgpu"
with open(tmp, "w", encoding="utf-8") as f: json.dump(d, f, separators=(",", ":"))
os.replace(tmp, state)
if undo: os.path.exists(side) and os.remove(side)
else:
    prev = json.load(open(side)).get("added", []) if os.path.exists(side) else []
    json.dump({"added": sorted(set(prev + what)), "by": "drAIML WebGPU helper"}, open(side, "w"))
PY
)
  echo "• $dir — $out"
  [[ "$out" == unchanged ]] || changed=$((changed+1))
}

MARK_A="// >>> drAIML WebGPU helper"; MARK_B="// <<< drAIML WebGPU helper"
firefox() {
  local prof="$1" uj="$1/user.js"
  [ -f "$prof/prefs.js" ] || return 0
  # Linux: the "lock" symlink names the PID. macOS uses .parentlock (no PID), so there any running Firefox counts
  if running "$prof/lock" || flatpak_running "$prof" || { [ "$OS" = Darwin ] && pgrep -xq firefox; }; then
    echo "• $prof — Firefox is running: close it and run this again"; skipped=$((skipped+1)); return 0
  fi
  if [ "$UNDO" = 1 ]; then
    grep -qF "$MARK_A" "$uj" 2>/dev/null || { echo "• $prof — unchanged"; return 0; }
    echo "• $prof — $([ "$DRY" = 1 ] && echo "would remove" || echo "remove") dom.webgpu.enabled"
    [ "$DRY" = 1 ] && return 0
    local had=no
    grep -q "^// had-pref: yes" "$uj" && had=yes
    sed -i.bak-webgpu "/$(printf '%s' "$MARK_A" | sed 's/[\/&]/\\&/g')/,/$(printf '%s' "$MARK_B" | sed 's/[\/&]/\\&/g')/d" "$uj"
    # Firefox copied our value into prefs.js; drop it there too, unless the setting was already yours before
    [ "$had" = no ] && sed -i.bak-webgpu '/"dom\.webgpu\.enabled"/d' "$prof/prefs.js"
  else
    grep -qF "$MARK_A" "$uj" 2>/dev/null && { echo "• $prof — unchanged"; return 0; }
    echo "• $prof — $([ "$DRY" = 1 ] && echo "would add" || echo "add") dom.webgpu.enabled = true"
    [ "$DRY" = 1 ] && return 0
    local had=no
    grep -q '"dom\.webgpu\.enabled"' "$prof/prefs.js" && had=yes
    printf '%s\n// had-pref: %s\nuser_pref("dom.webgpu.enabled", true);\n%s\n' "$MARK_A" "$had" "$MARK_B" >> "$uj"
  fi
  changed=$((changed+1))
}

echo "drAIML WebGPU installer — $([ "$UNDO" = 1 ] && echo undo || echo "flags: ${FLAGS[*]}")$([ "$DRY" = 1 ] && echo " (dry run)")"
if [ -n "$ONLY" ]; then
  if [ -f "$ONLY/Local State" ]; then chromium "$ONLY"; elif [ -f "$ONLY/prefs.js" ]; then firefox "$ONLY"
  else echo "$ONLY is neither a Chromium user-data directory nor a Firefox profile" >&2; exit 2; fi
else
  for d in "${CHROMIUM_DIRS[@]}"; do chromium "$d"; done
  if [ "$FIREFOX" = 1 ]; then
    for r in "${FIREFOX_ROOTS[@]}"; do [ -d "$r" ] && for p in "$r"/*/; do firefox "${p%/}"; done; done
  fi
fi

if [ "$OS" = Linux ] && [ "$UNDO" = 0 ]; then
  icds=$(find /usr/share/vulkan/icd.d /etc/vulkan/icd.d "$HOME/.local/share/vulkan/icd.d" -name '*.json' 2>/dev/null | head -1 || true)
  if [ -z "$icds" ]; then
    echo
    echo "No Vulkan driver found. WebGPU on Linux runs on Vulkan. Install one, for example (Debian/Ubuntu):"
    echo "  sudo apt install mesa-vulkan-drivers vulkan-tools && vulkaninfo --summary"
  fi
fi
echo
if [ "$changed" -gt 0 ] && [ "$DRY" = 0 ]; then echo "Done: $changed changed. Start the browser and run the WebGPU helper's check again."
  if [ "$skipped" -gt 0 ]; then echo "$skipped running browser(s) were skipped: close them and run this again for those."; fi
elif [ "$skipped" -gt 0 ]; then echo "Nothing changed for $skipped running browser(s). Close them and run again."; exit 3
else echo "Nothing to change."; fi
