#!/bin/sh
# One command that sets up Browser Workflow for the AI apps on this computer: the ChatGPT desktop app
# (Codex), the Claude desktop app, Claude Code and Antigravity. Both parts go in: the address of the
# Browser Workflow server, and the app that runs workflows in your own Chrome. (In the Claude desktop
# app the address is added by the user, in Settings, Connectors: that list is kept in their Claude
# account. The app can also be installed there from the Download button in the chat.)
#
#   curl -fsSL https://browser-workflow.web.app/install.sh | sh                  install (or update: see below)
#   curl -fsSL https://browser-workflow.web.app/install.sh | sh -s -- --remove   take everything out again
#
# Install, and nothing else:
#   1. looks for the AI apps. With none of them here it stops, and nothing is downloaded or changed
#   2. ChatGPT app, Antigravity: downloads the app from its GitHub releases into ~/.browser-workflow-app,
#      finds a Node.js to run it with (the one inside the ChatGPT app, or yours if it is 22 or newer;
#      with none, one is downloaded from nodejs.org into ~/.browser-workflow-node, checked against the
#      published checksum),
#      and adds Browser Workflow to their settings, after saving a copy of the file next to it:
#        ChatGPT desktop app   ~/.codex/config.toml
#        Claude desktop app    claude_desktop_config.json, in the folder it keeps its settings in
#        Antigravity           ~/.gemini/config/mcp_config.json
#      Each gets a data folder of its own (~/.browser-workflow-chatgpt, -antigravity), so they never
#      share a link to an account
#      The app is all an AI app gets: it has Browser Workflow's tools itself and asks the server for
#      an account of its own, so there is no address of the server to add, nothing to sign in to and
#      no computer to link. BW_ALONE=0 before "sh" asks for the earlier way instead (the address is
#      added, then a sign-in and "Link this computer" in the AI app): for someone who already has an
#      account with a username
#   3. Claude Code: installs the plugin browser-workflow (from the marketplace browser-workflow-bridge),
#      which brings both parts. Run again, it fetches the newest. The plugin was called
#      browser-workflow-bridge before: an install under that name is replaced
# What is left is to quit the AI app, open it again and ask for a workflow.
#
# Run again, it updates: with the newest version installed it says so and downloads nothing; with an
# older one it shows both versions and asks before installing the new one (Enter is yes). With nobody
# to ask it installs. BW_UPDATE=yes or no answers ahead of the question.
#
# Remove takes out everything install and use put on this computer, for a clean start:
#   the app's files, Browser Workflow's entries in those settings (also an address added by hand),
#   the data folders (the link to the account, the saved runs), the ChatGPT app's sign-in to Browser
#   Workflow (the system keychain or keyring), the copies of the settings files made here, and the
#   Claude Code plugin with its data. An account with no username is reachable only through that
#   sign-in: its workflows cannot be reached again afterwards.
# When something goes wrong it asks whether to send a report to Browser Workflow, and sends nothing
# without a yes: what it printed, the system's version and which AI apps it found, with the home
# folder's name taken out. An install that goes well sends nothing. BW_REPORT=yes or no answers
# ahead of the question.
# macOS and Linux. Windows has install.ps1, which does the same in PowerShell.
set -eu

SERVER="${BW_SERVER_URL:-https://browser-workflow-294054962898.us-central1.run.app}"
RELEASE="${BW_APP_URL:-https://github.com/chauvoluuhuong/browser-workflow-bridge/releases/latest/download/browser-workflow.mcpb}"
APP="$HOME/.browser-workflow-app"
CODEX="${BW_CODEX_CONFIG:-$HOME/.codex/config.toml}"
ANTIGRAVITY="${BW_ANTIGRAVITY_CONFIG:-$HOME/.gemini/config/mcp_config.json}"
# Where the ChatGPT app is looked for, and the Claude Code command ("none": do not look). For tests.
CHATGPT_APPS="${BW_CHATGPT_APPS-/Applications/ChatGPT.app:/usr/lib/chatgpt:/opt/ChatGPT}"
CLAUDE="${BW_CLAUDE-$(command -v claude 2>/dev/null || true)}"
[ "$CLAUDE" = "none" ] && CLAUDE=""
PLUGIN="browser-workflow@browser-workflow"
# The plugin's name until 1.1.1: replaced on install, and taken out on remove.
OLD_PLUGIN="browser-workflow-bridge@browser-workflow"
REMOVE=0
[ "${1:-}" = "--remove" ] && REMOVE=1

# What a report holds, if the user agrees to send one: the lines printed, and the step it stopped at.
VERSION="2026-10-14.2"
REPORT_URL="${BW_REPORT_URL:-$SERVER/install-report}"
LOG="$(mktemp)"
STEP="starting"
WHY=""
FOUND=""
TMP=""
# Highlighting for interactive terminals (kept off in pipes, non-interactive runs and when NO_COLOR is set).
USE_COLOR=0
C_BOLD=""
C_GREEN=""
C_YELLOW=""
C_RED=""
C_CYAN=""
C_RESET=""
if [ -t 1 ] && [ "${TERM:-dumb}" != "dumb" ] && [ -z "${NO_COLOR:-}" ]; then
  USE_COLOR=1
  C_BOLD="$(printf '\033[1m')"
  C_GREEN="$(printf '\033[32m')"
  C_YELLOW="$(printf '\033[33m')"
  C_RED="$(printf '\033[31m')"
  C_CYAN="$(printf '\033[36m')"
  C_RESET="$(printf '\033[0m')"
fi

say() { printf '%s\n' "$*"; printf '%s\n' "$*" >> "$LOG"; }
fail() { WHY="$*"; printf '\nBrowser Workflow was not installed: %s\n' "$*" >&2; printf 'Browser Workflow was not installed: %s\n' "$*" >> "$LOG"; exit 1; }

# A text as it goes inside a JSON string: without the home folder's name, on one line.
json_text() {
  printf '%s' "$1" | sed "s|$HOME|~|g" | tr '\t' ' ' | tr -d '\000-\010\013-\037' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | awk 'NR > 1 { printf "\\n" } { printf "%s", $0 }'
}
# Something went wrong: a report, only if the user says yes. Where there is nobody to ask, nothing is sent.
offer_report() {
  answer="${BW_REPORT:-}"
  if [ -z "$answer" ]; then
    # The command is piped into sh, so the answer is read from the terminal itself.
    { [ -t 1 ] && [ -r /dev/tty ]; } || return 0
    if [ "$USE_COLOR" = 1 ]; then
      printf '\n%s👉%s %sWould you like to send a report to Browser Workflow?%s [y/N]: ' \
        "$C_BOLD$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
    else
      printf '\nWould you like to send a report to Browser Workflow? [y/N]: '
    fi
    read -r answer < /dev/tty || return 0
  fi
  case "$answer" in [Yy]*) ;; *) return 0 ;; esac
  system="$(uname -srm 2>/dev/null || true)"
  if command -v sw_vers >/dev/null 2>&1; then system="macOS $(sw_vers -productVersion 2>/dev/null || true), $system"; fi
  [ "$REMOVE" = 1 ] && FOUND="${FOUND:-none} (removing)"
  body="{\"installer\":\"unix\",\"version\":\"$VERSION\",\"system\":\"$(json_text "$system")\",\"found\":\"$(json_text "${FOUND:-none}")\",\"step\":\"$(json_text "$STEP")\",\"error\":\"$(json_text "$1")\",\"log\":\"$(json_text "$(cat "$LOG" 2>/dev/null || true)")\"}"
  id="$(printf '%s' "$body" | curl -fsS -m 10 -H 'content-type: application/json' --data-binary @- "$REPORT_URL" 2>/dev/null | sed -n 's/.*"id":"\([^"]*\)".*/\1/p' || true)"
  if [ -n "$id" ]; then printf '%s\n' "Sent, thank you. If you write to us about this, mention report $id."; else printf '%s\n' "The report could not be sent."; fi
}
# However it ends: the temporary files go, and an install that did not end well offers the report.
finish() {
  code=$?
  trap - EXIT
  if [ "$code" != 0 ]; then offer_report "${WHY:-it stopped unexpectedly, with code $code}" || true; fi
  [ -n "${TMP-}" ] && rm -rf "$TMP"
  rm -f "${RESULTS-}" "${LOG-}"
  exit "$code"
}
trap finish EXIT
# Versions ("1.2.0"): the one a package.json or plugin.json names, and whether the first is older than the second.
version_of() { sed -n 's/^[[:space:]]*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" 2>/dev/null | head -1; }
older() { awk -v a="$1" -v b="$2" 'BEGIN { split(a, x, "."); split(b, y, "."); for (i = 1; i <= 3; i++) { if (x[i] + 0 < y[i] + 0) exit 0; if (x[i] + 0 > y[i] + 0) exit 1 } exit 1 }'; }
# The newest version of the app, from where its download is published; nothing when it can't be told
# (offline, or a download of one's own in BW_APP_URL). BW_LATEST_APP says it instead (tests).
latest_app() {
  if [ -n "${BW_LATEST_APP+x}" ]; then printf '%s' "$BW_LATEST_APP"; return 0; fi
  [ -n "${BW_APP_URL:-}" ] && return 0
  curl -fsS -m 10 -o /dev/null -w '%{redirect_url}' https://github.com/chauvoluuhuong/browser-workflow-bridge/releases/latest 2>/dev/null | sed -n 's|.*/tag/v\{0,1\}\([^/]*\)$|\1|p' || true
}
# A newer version than the one installed: install it? Yes unless the answer is no. The command is
# piped into sh, so the answer is read from the terminal itself; with nobody to ask, it is yes.
want_update() {
  answer="${BW_UPDATE:-}"
  if [ -z "$answer" ]; then
    { [ -t 1 ] && [ -r /dev/tty ]; } || return 0
    printf '\n%s: version %s is available (you have %s). Install it? [Y/n] ' "$1" "$3" "$2"
    read -r answer < /dev/tty || return 0
  fi
  printf '%s: version %s is available (you have %s). Install it? %s\n' "$1" "$3" "$2" "${answer:-yes}" >> "$LOG"
  case "$answer" in [Nn]*) return 1 ;; *) return 0 ;; esac
}
new_enough() { [ -x "$1" ] && [ "$("$1" -p 'Number(process.versions.node.split(".")[0]) >= 22' 2>/dev/null)" = "true" ]; }

# ---- which AI apps are here -------------------------------------------------------------------
STEP="looking for the AI apps"
HAS_CHATGPT=0
[ -d "$(dirname "$CODEX")" ] && HAS_CHATGPT=1
OLD_IFS=$IFS; IFS=:
for p in $CHATGPT_APPS; do [ -n "$p" ] && [ -e "$p" ] && HAS_CHATGPT=1; done
IFS=$OLD_IFS
HAS_ANTIGRAVITY=0
[ -f "$ANTIGRAVITY" ] && HAS_ANTIGRAVITY=1
HAS_CLAUDE=0
[ -n "$CLAUDE" ] && [ -x "$CLAUDE" ] && HAS_CLAUDE=1
# The Claude desktop app, by the folder it keeps its settings in ("none": do not look. For tests).
CLAUDE_APP=""
if [ "${BW_CLAUDE_APP_DIRS-}" != "none" ]; then
  OLD_IFS=$IFS; IFS=:
  for d in ${BW_CLAUDE_APP_DIRS:-$HOME/Library/Application Support/Claude:$HOME/.config/Claude}; do
    if [ -n "$d" ] && [ -d "$d" ]; then CLAUDE_APP="${CLAUDE_APP:+$CLAUDE_APP:}$d"; fi
  done
  IFS=$OLD_IFS
fi
HAS_CLAUDE_APP=0
[ -n "$CLAUDE_APP" ] && HAS_CLAUDE_APP=1

[ "$HAS_CHATGPT" = 1 ] && FOUND="ChatGPT app"
[ "$HAS_CLAUDE_APP" = 1 ] && FOUND="${FOUND:+$FOUND, }Claude app"
[ "$HAS_ANTIGRAVITY" = 1 ] && FOUND="${FOUND:+$FOUND, }Antigravity"
[ "$HAS_CLAUDE" = 1 ] && FOUND="${FOUND:+$FOUND, }Claude Code"
if [ "$REMOVE" = 0 ] && [ "$HAS_CHATGPT$HAS_CLAUDE_APP$HAS_ANTIGRAVITY$HAS_CLAUDE" = "0000" ]; then
  fail "no AI app that this command sets up was found on this computer (the ChatGPT desktop app, the Claude desktop app or Claude Code). Install one of them, open it once, and run this again. Nothing was downloaded or changed."
fi

# ---- a Node.js, 22 or newer: it runs the app, and it edits the settings files -------------------
STEP="finding Node.js"
OWN_NODE="$HOME/.browser-workflow-node"
NODE=""
# Where a Node.js is looked for ("none": nowhere, so that one is downloaded. For tests).
if [ "${BW_NODES-}" != "none" ]; then
  for candidate in \
    "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node" \
    "/usr/lib/chatgpt/resources/cua_node/bin/node" \
    "/opt/ChatGPT/resources/cua_node/bin/node" \
    "$(command -v node 2>/dev/null || true)" \
    "$OWN_NODE/node" \
    "/opt/homebrew/bin/node" "/usr/local/bin/node"; do
    if [ -n "$candidate" ] && new_enough "$candidate"; then NODE="$candidate"; break; fi
  done
fi
# None here: one is downloaded for the app alone, and checked against what nodejs.org published. It is not added to PATH.
get_node() {
  case "$(uname -s)-$(uname -m)" in
    Darwin-arm64) kind="darwin-arm64" ;;
    Darwin-x86_64) kind="darwin-x64" ;;
    Linux-x86_64) kind="linux-x64" ;;
    Linux-aarch64 | Linux-arm64) kind="linux-arm64" ;;
    *) WHY="there is no Node.js to download for this kind of computer ($(uname -sm))"; return 1 ;;
  esac
  site="${BW_NODE_SITE:-https://nodejs.org/dist/latest-v22.x}"
  sums="$(curl -fsSL "$site/SHASUMS256.txt")" || { WHY="the download of Node.js failed. Check the internet connection and run this again"; return 1; }
  line="$(printf '%s\n' "$sums" | grep -E "  node-v[0-9.]+-$kind\.tar\.gz\$" | head -1)"
  [ -n "$line" ] || { WHY="the list of Node.js downloads could not be read"; return 1; }
  sum="${line%% *}"
  name="${line##* }"
  work="$(mktemp -d)"
  curl -fsSL -o "$work/node.tar.gz" "$site/$name" || { rm -rf "$work"; WHY="the download of Node.js failed. Check the internet connection and run this again"; return 1; }
  if command -v shasum >/dev/null 2>&1; then got="$(shasum -a 256 "$work/node.tar.gz" | cut -d' ' -f1)"; else got="$(sha256sum "$work/node.tar.gz" | cut -d' ' -f1)"; fi
  [ "$got" = "$sum" ] || { rm -rf "$work"; WHY="the Node.js that was downloaded is not the one nodejs.org published"; return 1; }
  tar -xzf "$work/node.tar.gz" -C "$work" "${name%.tar.gz}/bin/node" || { rm -rf "$work"; WHY="the Node.js download could not be opened"; return 1; }
  mkdir -p "$OWN_NODE"
  mv "$work/${name%.tar.gz}/bin/node" "$OWN_NODE/node"
  chmod +x "$OWN_NODE/node"
  rm -rf "$work"
  new_enough "$OWN_NODE/node" || { WHY="the Node.js that was downloaded does not start on this computer"; return 1; }
}
SKIPPED=""
if [ -z "$NODE" ] && [ "$REMOVE" = 0 ] && [ "$HAS_CHATGPT$HAS_CLAUDE_APP$HAS_ANTIGRAVITY" != "000" ]; then
  STEP="downloading Node.js"
  say "Downloading Node.js, which runs the app (about 50 MB, once)…"
  if get_node; then NODE="$OWN_NODE/node"
  else
    # Claude Code needs none of this: it still gets its plugin.
    [ "$HAS_CLAUDE" = 1 ] || fail "$WHY. Nothing was changed."
    SKIPPED="The desktop apps (ChatGPT, Claude, Antigravity): skipped, $WHY"
    HAS_CHATGPT=0; HAS_CLAUDE_APP=0; HAS_ANTIGRAVITY=0
  fi
  WHY=""
fi

# ---- the app's files (only the ChatGPT app and Antigravity start them from this folder) ---------
RESULTS="$(mktemp)"
TMP="$(mktemp -d)"
get_app() {
  curl -fsSL -o "$TMP/app.zip" "$RELEASE" || { WHY="the download failed. Check the internet connection and run this again"; return 1; }
  mkdir "$TMP/app"
  if command -v unzip >/dev/null 2>&1; then unzip -q "$TMP/app.zip" -d "$TMP/app" || { WHY="the download could not be opened"; return 1; }
  elif command -v python3 >/dev/null 2>&1; then python3 -m zipfile -e "$TMP/app.zip" "$TMP/app" || { WHY="the download could not be opened"; return 1; }
  else WHY="neither unzip nor python3 is on this computer to open the download"; return 1; fi
  [ -f "$TMP/app/src/index.js" ] || { WHY="the download is not the app (no src/index.js in it)"; return 1; }
  rm -rf "$APP.old"
  if [ -d "$APP" ]; then mv "$APP" "$APP.old"; fi
  mv "$TMP/app" "$APP"
  rm -rf "$APP.old"
}
GET_APP=1
if [ "$REMOVE" = 0 ] && [ "$HAS_CHATGPT$HAS_CLAUDE_APP$HAS_ANTIGRAVITY" != "000" ] && [ -f "$APP/src/index.js" ]; then
  STEP="looking for a newer version of the app"
  HAVE="$(version_of "$APP/package.json")"
  NEWEST="$(latest_app)"
  if [ -n "$HAVE" ] && [ -n "$NEWEST" ]; then
    if ! older "$HAVE" "$NEWEST"; then
      GET_APP=0
      say "The Browser Workflow app is up to date ($HAVE)."
    elif ! want_update "The Browser Workflow app" "$HAVE" "$NEWEST"; then
      GET_APP=0
      printf '! The Browser Workflow app: kept version %s. Version %s is there whenever you want it: run this command again\n' "$HAVE" "$NEWEST" >> "$RESULTS"
    fi
  fi
fi
if [ "$REMOVE" = 0 ] && [ "$GET_APP" = 1 ] && [ "$HAS_CHATGPT$HAS_CLAUDE_APP$HAS_ANTIGRAVITY" != "000" ]; then
  STEP="downloading the app"
  say "Downloading the Browser Workflow app…"
  WHY=""
  if ! get_app; then
    # Claude Code needs none of this: it still gets its plugin.
    [ "$HAS_CLAUDE" = 1 ] || fail "$WHY. Nothing was changed."
    printf '✗ The desktop apps (ChatGPT, Claude, Antigravity): not installed, %s\n' "$WHY" >> "$RESULTS"
    HAS_CHATGPT=0; HAS_CLAUDE_APP=0; HAS_ANTIGRAVITY=0
  fi
fi

[ -n "$SKIPPED" ] && printf '! %s\n' "$SKIPPED" >> "$RESULTS"

# A copy of the app that an AI app started earlier is still running, and writes its data folder back
# after it is deleted: on remove it is stopped first, and what it wrote in between is swept at the end.
stop_app() { pkill -f "$APP/src/index.js" >/dev/null 2>&1 || true; }
if [ "$REMOVE" = 1 ]; then stop_app; sleep 1; fi

# ---- the Claude app has to be closed first ------------------------------------------------------
# It keeps its settings in memory and writes them back: what is changed in the file while it is open
# is gone the next time it does (an entry added is lost, an entry removed comes back). So the command
# waits here for it to be quit. BW_CLAUDE_APP_WAIT: how many seconds at most (for tests).
# BW_CLAUDE_APP_OPEN (for tests): a file that stands for the app; it is "open" for as long as the file is there.
claude_app_open() {
  if [ -n "${BW_CLAUDE_APP_OPEN-}" ]; then [ -e "$BW_CLAUDE_APP_OPEN" ]; return; fi
  # Read from the list of processes: pgrep leaves out the programs this command was started from.
  ps ax -o args= 2>/dev/null | grep -q -e "[C]laude.app/Contents/MacOS/Claude" -e "[c]laude-desktop/claude-desktop"
}
CLAUDE_OPEN=""
if [ -n "$CLAUDE_APP" ] && { [ "$REMOVE" = 1 ] || [ "$HAS_CLAUDE_APP" = 1 ]; } && claude_app_open; then
  STEP="waiting for the Claude app to be quit"
  say ""
  if [ "$USE_COLOR" = 1 ]; then
    printf '%s👉%s %sThe Claude app is open: quit it completely now (on a Mac: Command + Q) to continue.%s\n' "$C_BOLD$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
    printf 'The Claude app is open: quit it completely now (on a Mac: Command + Q) to continue.\n' >> "$LOG"
  else
    say "The Claude app is open: quit it completely now (on a Mac: Command + Q) to continue."
  fi
  waited=0
  while claude_app_open && [ "$waited" -lt "${BW_CLAUDE_APP_WAIT:-300}" ]; do sleep 2; waited=$((waited + 2)); done
  if claude_app_open; then
    CLAUDE_OPEN="Claude app: nothing was changed in it, because it is still open. Quit it completely and run this again"
    CLAUDE_APP=""; HAS_CLAUDE_APP=0
  else
    sleep 1
    if [ "$USE_COLOR" = 1 ]; then
      printf '%s✓ It is closed. Going on.%s\n' "$C_BOLD$C_GREEN" "$C_RESET"
      printf 'It is closed. Going on.\n' >> "$LOG"
    else
      say "It is closed. Going on."
    fi
  fi
fi

# ---- the ChatGPT app's and Antigravity's settings, data and sign-in -----------------------------
STEP="changing the settings of the AI apps"
if [ -n "$NODE" ] && { [ "$REMOVE" = 1 ] || [ "$HAS_CHATGPT$HAS_CLAUDE_APP$HAS_ANTIGRAVITY" != "000" ]; }; then
BW_NODE="$NODE" BW_APP="$APP" BW_SERVER="$SERVER" BW_CODEX="$CODEX" BW_ANTIGRAVITY="$ANTIGRAVITY" BW_REMOVE="$REMOVE" \
BW_HAS_CHATGPT="$HAS_CHATGPT" BW_HAS_ANTIGRAVITY="$HAS_ANTIGRAVITY" BW_CLAUDE_APP="$CLAUDE_APP" BW_HAS_CLAUDE_APP="$HAS_CLAUDE_APP" BW_RESULTS="$RESULTS" "$NODE" - <<'NODE_SCRIPT'
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const { BW_NODE: node, BW_APP: app, BW_SERVER: server, BW_CODEX: codex, BW_ANTIGRAVITY: antigravity } = process.env;
const remove = process.env.BW_REMOVE === '1';
// Alone: the app is the only thing the AI app gets. It has the tools itself and an account of its own, so no address of the
// server is added, and there is nothing to sign in to or to link. BW_ALONE=0 asks for the earlier way: the address, a sign-in, a link.
const alone = process.env.BW_ALONE !== '0';
const entry = path.join(app, 'src', 'index.js');
const linux = process.platform === 'linux';
const home = os.homedir();
const ours = `${server}/mcp`;
const result = (mark, text) => fs.appendFileSync(process.env.BW_RESULTS, `${mark} ${text}\n`);
const COPY = '.before-browser-workflow';
/** Our copies of a settings file: one is kept (what the file was before the last change); remove deletes them all. */
const copies = (file) => {
  try { return fs.readdirSync(path.dirname(file)).filter((n) => n.startsWith(path.basename(file) + COPY)).map((n) => path.join(path.dirname(file), n)); } catch { return []; }
};
const save = (file, text) => {
  for (const c of copies(file)) fs.rmSync(c, { force: true });
  if (fs.existsSync(file)) fs.copyFileSync(file, file + COPY);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  const tmp = `${file}.tmp-${process.pid}`;
  fs.writeFileSync(tmp, text, { mode: 0o600 });
  fs.renameSync(tmp, file);
};
const running = (pattern) => { try { return execFileSync('pgrep', ['-f', pattern], { encoding: 'utf8' }).trim().length > 0; } catch { return false; } };
const gone = (dir) => { if (!fs.existsSync(dir)) return false; fs.rmSync(dir, { recursive: true, force: true }); return true; };

/** A TOML text without the tables `drop(name, body)` says yes to. A table runs from its "[header]" line to the next. */
function withoutTables(text, drop) {
  const lines = text.split('\n'), out = [], names = [];
  let skipping = false;
  for (let i = 0; i < lines.length; i++) {
    const header = /^\s*\[\[?([^\]]+)\]\]?\s*$/.exec(lines[i]);
    if (header) {
      let end = i + 1;
      while (end < lines.length && !/^\s*\[/.test(lines[end])) end++;
      skipping = drop(header[1].trim(), lines.slice(i, end).join('\n'));
      if (skipping) names.push(header[1].trim());
    }
    if (!skipping) out.push(lines[i]);
  }
  return { text: out.join('\n').replace(/\n{3,}/g, '\n\n'), names };
}
/** "mcp_servers.name" or "mcp_servers."name"" → name; nothing for any other table, and for a table inside one. */
const serverName = (table) => /^mcp_servers\.("?)([^".]+)\1$/.exec(table)?.[2];
const inside = (table, names) => names.some((n) => table.startsWith(`mcp_servers.${n}.`) || table.startsWith(`mcp_servers."${n}".`));

/** The ChatGPT app's sign-in to Browser Workflow: in the keychain (Mac) or the keyring (Linux), under "<entry name>|…". */
function forgetSignIn(names) {
  if (process.env.BW_KEEP_SIGNIN === '1') return;
  const service = 'Codex MCP Credentials';
  const mine = (account) => names.includes(account.split('|')[0]);
  let n = 0;
  try {
    if (process.platform === 'darwin') {
      const dump = execFileSync('security', ['dump-keychain'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 });
      for (const block of dump.split('keychain: ')) {
        if (!block.includes(`"svce"<blob>="${service}"`)) continue;
        const account = /"acct"<blob>="([^"]+)"/.exec(block)?.[1];
        if (account && mine(account)) { execFileSync('security', ['delete-generic-password', '-s', service, '-a', account], { stdio: 'ignore' }); n++; }
      }
    } else {
      // secret-tool prints an item's attributes on its error output, and the secret itself on the other: only the first is read.
      const found = spawnSync('secret-tool', ['search', '--all', 'service', service], { encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'] }).stderr ?? '';
      for (const m of found.matchAll(/^attribute\.username = (.+)$/gm)) {
        if (mine(m[1])) { execFileSync('secret-tool', ['clear', 'service', service, 'username', m[1]], { stdio: 'ignore' }); n++; }
      }
      // Without a keyring the ChatGPT app keeps it in a file.
      const file = path.join(path.dirname(codex), '.credentials.json');
      if (fs.existsSync(file)) {
        const all = JSON.parse(fs.readFileSync(file, 'utf8'));
        const keys = Object.keys(all).filter((k) => mine(k) || JSON.stringify(all[k]).includes(ours));
        if (keys.length) { for (const k of keys) delete all[k]; fs.writeFileSync(file, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 }); n += keys.length; }
      }
    }
  } catch { /* no keychain to reach: said below */ }
  return n;
}

// ---- ChatGPT desktop app: TOML tables ----
if (remove || process.env.BW_HAS_CHATGPT === '1') {
  const BEGIN = '# >>> Browser Workflow (added by its install command)';
  const END = '# <<< Browser Workflow';
  const before = fs.existsSync(codex) ? fs.readFileSync(codex, 'utf8') : '';
  // The ChatGPT app rewrites this file and adds tables of its own between our two lines, so they only mark; tables are found by what they hold.
  const unmarked = before.split('\n').filter((l) => l.trim() !== BEGIN && l.trim() !== END).join('\n');
  const open = running(process.platform === 'darwin' ? 'ChatGPT.app/Contents/MacOS/ChatGPT' : '/chatgpt/');
  if (remove) {
    const names = [];
    const first = withoutTables(unmarked, (table, body) => {
      const name = serverName(table);
      if (name && (body.includes(ours) || body.includes(app))) { names.push(name); return true; }
      return false;
    });
    const rest = withoutTables(first.text, (table) => inside(table, names)).text;
    const had = names.length > 0 || rest.trim() !== before.trim();
    if (had) { save(codex, rest.replace(/\n*$/, '\n')); }
    for (const c of copies(codex)) fs.rmSync(c, { force: true });
    const signIn = forgetSignIn([...new Set([...names, 'browser_workflow'])]);
    const data = gone(path.join(home, '.browser-workflow-chatgpt'));
    if (had || data || signIn) {
      result('✓', `ChatGPT app: removed${had ? ' from its settings' : ''}${data ? ', with its data folder' : ''}${signIn ? ', and its sign-in forgotten' : ''}${open ? '. It is open: quit it and open it again' : ''}`);
    }
  } else {
    // Ours to replace: the table that starts the app from our folder, and its env table. A "browser_workflow_app" that starts something else is someone's own.
    const own = /^\[mcp_servers\.browser_workflow_app\]/m.test(unmarked) && !withoutTables(unmarked, (table, body) => table === 'mcp_servers.browser_workflow_app' && body.includes(app)).names.length;
    if (own) result('!', 'ChatGPT app: it already has a "browser_workflow_app" entry of its own, left as it is');
    else {
      let rest = withoutTables(unmarked, (table) => table === 'mcp_servers.browser_workflow_app' || table === 'mcp_servers.browser_workflow_app.env').text;
      const s = JSON.stringify;
      // Alone, an address of ours that is already there goes: the tools would show twice.
      if (alone) rest = withoutTables(rest, (table, body) => !!serverName(table) && body.includes(ours)).text;
      const hasServer = alone || rest.includes(ours);
      const lines = [
        BEGIN,
        ...(hasServer ? [] : ['[mcp_servers.browser_workflow]', `url = ${s(ours)}`, '']),
        '[mcp_servers.browser_workflow_app]',
        `command = ${s(node)}`,
        `args = [${s(entry)}]`,
        // The ChatGPT app starts it with a short list of settings: without DISPLAY no Chrome window opens on Linux.
        ...(linux ? ['env_vars = ["DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR"]'] : []),
        '',
        '[mcp_servers.browser_workflow_app.env]',
        `BW_SERVER_URL = ${s(server)}`,
        `BW_DATA_DIR = ${s(path.join(home, '.browser-workflow-chatgpt'))}`,
        `BW_ALONE = ${s(alone ? '1' : '0')}`,
        END,
      ];
      save(codex, `${rest.trim() ? `${rest.replace(/\n*$/, '\n')}\n` : ''}${lines.join('\n')}\n`);
      result('✓', `ChatGPT app: installed. ${open ? 'Quit it and open it again' : 'Open it'}. ${alone ? 'Then start a new chat: there is nothing to sign in to and nothing to link' : `${hasServer ? 'If it asks you to sign in to Browser Workflow' : 'Then sign in to Browser Workflow'}: Settings, Plugins, Browser Workflow, Authenticate, then Continue on the page that opens. Then start a new chat`}`);
    }
  }
}

// ---- Antigravity: a JSON file of servers ----
if (fs.existsSync(antigravity) && (remove || process.env.BW_HAS_ANTIGRAVITY === '1')) {
  const raw = fs.readFileSync(antigravity, 'utf8');
  let config;
  try { config = raw.trim() ? JSON.parse(raw) : {}; } catch { config = undefined; }
  if (!config) result('!', `Antigravity: ${antigravity} is not valid JSON, left as it is`);
  else {
    config.mcpServers ??= {};
    const points = (v) => [v?.serverUrl, v?.url, v?.httpUrl].includes(ours);
    if (remove) {
      const names = Object.entries(config.mcpServers).filter(([, v]) => points(v) || (v?.args ?? []).some((a) => String(a).includes(app))).map(([k]) => k);
      for (const k of names) delete config.mcpServers[k];
      if (names.length) save(antigravity, `${JSON.stringify(config, null, 2)}\n`);
      for (const c of copies(antigravity)) fs.rmSync(c, { force: true });
      const data = gone(path.join(home, '.browser-workflow-antigravity'));
      if (names.length || data) result('✓', `Antigravity: removed${names.length ? ' from its settings' : ''}${data ? ', with its data folder' : ''}. Quit it and open it again`);
    } else {
      const had = 'browser-workflow-app' in config.mcpServers;
      if (alone) { for (const [k, v] of Object.entries(config.mcpServers)) if (points(v)) delete config.mcpServers[k]; }
      else if (!Object.values(config.mcpServers).some(points)) config.mcpServers['browser-workflow'] = { serverUrl: ours };
      const env = { BW_SERVER_URL: server, BW_DATA_DIR: path.join(home, '.browser-workflow-antigravity'), BW_ALONE: alone ? '1' : '0' };
      if (linux) for (const k of ['DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) if (process.env[k]) env[k] = process.env[k];
      config.mcpServers['browser-workflow-app'] = { command: node, args: [entry], env };
      save(antigravity, `${JSON.stringify(config, null, 2)}\n`);
      result('✓', `Antigravity: ${had ? 'updated' : 'installed'}. Quit it and open it again, then start a new conversation`);
    }
  }
}

// ---- Claude desktop app: a JSON file of servers, in each folder it keeps its settings in ----
const claudeApp = (process.env.BW_CLAUDE_APP ?? '').split(path.delimiter).filter(Boolean);
if (claudeApp.length && (remove || process.env.BW_HAS_CLAUDE_APP === '1')) {
  const NAME = 'Browser Workflow for Chrome'; // the name the extension has, so Claude sees the same tools either way
  let changed = 0, extension = false, theirs = false, replaced = false;
  // The extension's folder and settings go to ~/.browser-workflow-old-extension (nothing is deleted), and it comes off Claude's list.
  const putAwayExtension = (dir) => {
    const mine = (n) => /browser-workflow/i.test(n);
    const keep = path.join(home, '.browser-workflow-old-extension', String(Date.now()));
    const move = (from) => {
      if (!fs.existsSync(from)) return;
      fs.mkdirSync(keep, { recursive: true });
      const to = path.join(keep, path.basename(from));
      try { fs.renameSync(from, to); } catch { fs.cpSync(from, to, { recursive: true }); fs.rmSync(from, { recursive: true, force: true }); }
    };
    const registry = path.join(dir, 'extensions-installations.json');
    let reg;
    try { reg = JSON.parse(fs.readFileSync(registry, 'utf8').replace(/^\uFEFF/, '')); } catch { /* no list */ }
    const listed = reg?.extensions && typeof reg.extensions === 'object' ? Object.keys(reg.extensions).filter(mine) : [];
    let ids = [];
    try { ids = fs.readdirSync(path.join(dir, 'Claude Extensions')).filter(mine); } catch { /* no extensions */ }
    for (const id of ids) move(path.join(dir, 'Claude Extensions', id));
    for (const id of new Set([...ids, ...listed])) move(path.join(dir, 'Claude Extensions Settings', `${id}.json`));
    if (listed.length) {
      for (const id of listed) delete reg.extensions[id];
      save(registry, `${JSON.stringify(reg, null, 2)}\n`);
    }
  };
  for (const dir of claudeApp) {
    const file = path.join(dir, 'claude_desktop_config.json');
    // Installed from the Download button it is an extension: the earlier way, as it was on the day of that file. It needs the
    // connector, and this command can't update it, so installing puts it away and adds the newest app instead (with both, every
    // tool would show twice). Claude is closed by now, so it does not write its list of extensions back. The data folder stays,
    // so the account the extension was linked to stays too.
    let asExtension = false;
    try { asExtension = fs.readdirSync(path.join(dir, 'Claude Extensions')).some((n) => /browser-workflow/i.test(n)); } catch { /* no extensions */ }
    if (asExtension && !remove) { putAwayExtension(dir); replaced = true; asExtension = false; }
    if (asExtension) extension = true;
    let config = {};
    if (fs.existsSync(file)) {
      const raw = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
      try { config = raw.trim() ? JSON.parse(raw) : {}; } catch { config = undefined; }
    }
    if (!config || typeof config !== 'object' || Array.isArray(config)) { result('!', `Claude app: ${file} is not valid JSON, left as it is`); continue; }
    const servers = config.mcpServers && typeof config.mcpServers === 'object' ? config.mcpServers : {};
    const mine = Object.entries(servers).filter(([, v]) => (v?.args ?? []).some((a) => String(a).includes(app))).map(([k]) => k);
    for (const k of mine) delete servers[k];
    if (remove || asExtension) {
      if (mine.length) { config.mcpServers = servers; save(file, `${JSON.stringify(config, null, 2)}\n`); changed++; }
      if (remove) for (const c of copies(file)) fs.rmSync(c, { force: true });
    } else if (NAME in servers) theirs = true; // an entry with our name that starts something else is someone's own
    else {
      // Started by the Claude app it gets few settings: without DISPLAY no Chrome window opens on Linux.
      const env = { BW_SERVER_URL: server, BW_ALONE: alone ? '1' : '0' };
      if (linux) for (const k of ['DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) if (process.env[k]) env[k] = process.env[k];
      config.mcpServers = { ...servers, [NAME]: { command: node, args: [entry], env } };
      save(file, `${JSON.stringify(config, null, 2)}\n`);
      changed++;
    }
  }
  // It is closed: the command waited for that before it came here.
  const again = 'Open it';
  const byHand = 'Settings, Extensions, Advanced settings, Install Extension';
  if (remove) {
    // ~/.browser-workflow is also the extension's and Claude Code's: it stays while the extension is there (Claude Code's part is below).
    const data = !extension && gone(path.join(home, '.browser-workflow'));
    if (changed || data) result('✓', `Claude app: removed${changed ? ' from its settings' : ''}${data ? ', with its data folder' : ''}`);
    if (extension) result('!', 'Claude app: Browser Workflow is also in it as an extension. Remove it there: Settings, Extensions, Browser Workflow, Uninstall');
  } else if (extension) result('✓', `Claude app: it already has Browser Workflow, as an extension. To get the newest, download the file again and install it in Claude: ${byHand}`);
  else if (theirs) result('!', `Claude app: it already has a "${NAME}" entry of its own, left as it is`);
  else if (changed) result('✓', `Claude app: ${replaced ? 'the Browser Workflow extension was replaced by the newest app (the old one is in ~/.browser-workflow-old-extension)' : 'installed'}. ${again}, then start a new chat. ${alone ? 'There is nothing to sign in to and nothing to link. If Browser Workflow is already in Claude under Settings, Connectors, remove it there: the app has everything now' : `If Browser Workflow's address is not in Claude yet, add it first: Settings, Connectors, Add custom connector, ${ours}`}`);
}

if (remove && gone(app)) result('✓', 'The app\'s files: removed');
NODE_SCRIPT
elif [ "$REMOVE" = 1 ]; then
  # No Node.js to edit the settings files with: what is ours alone still goes.
  for d in "$APP" "$HOME/.browser-workflow-chatgpt" "$HOME/.browser-workflow-antigravity"; do
    [ -e "$d" ] && rm -rf "$d" && printf '✓ Removed %s\n' "$d" >> "$RESULTS"
  done
  if grep -qs "browser-workflow" "$CODEX" "$ANTIGRAVITY" 2>/dev/null; then
    printf '! No Node.js 22 or newer was found to edit the settings with: remove Browser Workflow in the AI app itself (ChatGPT: Settings, Plugins)\n' >> "$RESULTS"
  fi
fi

[ -n "$CLAUDE_OPEN" ] && printf '! %s\n' "$CLAUDE_OPEN" >> "$RESULTS"

# ---- Claude Code: the plugin brings the server's address and the app ----------------------------
STEP="setting up Claude Code"
if [ "$HAS_CLAUDE" = 1 ]; then
  LISTED="$("$CLAUDE" plugin list 2>/dev/null || true)"
  HAS_NEW=0; HAS_OLD=0
  printf '%s\n' "$LISTED" | grep -q " $PLUGIN" && HAS_NEW=1
  printf '%s\n' "$LISTED" | grep -q " $OLD_PLUGIN" && HAS_OLD=1
  if [ "$REMOVE" = 1 ]; then
    if [ "$HAS_NEW$HAS_OLD" != "00" ]; then
      for p in "$PLUGIN" "$OLD_PLUGIN"; do "$CLAUDE" plugin uninstall "$p" >/dev/null 2>&1 || true; done
      "$CLAUDE" plugin marketplace remove browser-workflow >/dev/null 2>&1 || true
      rm -rf "$HOME"/.claude/plugins/data/browser-workflow-bridge* "$HOME"/.claude/plugins/data/browser-workflow-browser-workflow*
      # ~/.browser-workflow is also the Claude desktop app's: it stays when that app has Browser Workflow installed.
      DESKTOP=""
      for d in "$HOME/Library/Application Support/Claude/Claude Extensions" "$HOME/.config/Claude/Claude Extensions"; do
        [ -d "$d" ] && ls "$d" 2>/dev/null | grep -qi "browser-workflow" && DESKTOP=1
      done
      if [ -z "$DESKTOP" ]; then rm -rf "$HOME/.browser-workflow"; printf '✓ Claude Code: the plugin and its data removed\n' >> "$RESULTS"
      else printf '✓ Claude Code: the plugin removed. The folder ~/.browser-workflow stays: the Claude desktop app uses it too\n' >> "$RESULTS"; fi
    fi
  elif ! new_enough "$(command -v node 2>/dev/null || echo /nonexistent)"; then
    printf '! Claude Code: skipped. Its plugin needs Node.js 22 or newer on this computer: install it from https://nodejs.org and run this again\n' >> "$RESULTS"
  else
    say "Adding Browser Workflow to Claude Code…"
    "$CLAUDE" plugin marketplace add chauvoluuhuong/browser-workflow-bridge >/dev/null 2>&1 || true
    # Added before, "add" succeeds and leaves Claude Code's copy of the plugin list as it was: "update" fetches the newest.
    "$CLAUDE" plugin marketplace update browser-workflow >/dev/null 2>&1 || true
    MANUAL="In Claude Code, type: /plugin marketplace add chauvoluuhuong/browser-workflow-bridge   then: /plugin marketplace update browser-workflow   then: /plugin install $PLUGIN"
    # The version installed (under the plugin's line in the list), and the newest, in Claude Code's copy of the marketplace.
    HAVE="$(printf '%s\n' "$LISTED" | awk -v p="$PLUGIN" 'index($0, "> " p) { f = 1; next } f && /Version:/ { print $2; exit } /^ *>/ { f = 0 }')"
    NEWEST="$(version_of "$HOME/.claude/plugins/marketplaces/browser-workflow/.claude-plugin/plugin.json")"
    if [ "$HAS_NEW" = 1 ] && [ -n "$HAVE" ] && [ -n "$NEWEST" ] && ! older "$HAVE" "$NEWEST"; then
      printf '✓ Claude Code: up to date (version %s)\n' "$HAVE" >> "$RESULTS"
    elif [ "$HAS_NEW" = 1 ] && [ -n "$HAVE" ] && [ -n "$NEWEST" ] && ! want_update "Browser Workflow in Claude Code" "$HAVE" "$NEWEST"; then
      printf '! Claude Code: kept version %s. Version %s is there whenever you want it: run this command again\n' "$HAVE" "$NEWEST" >> "$RESULTS"
    elif [ "$HAS_NEW" = 1 ]; then
      if "$CLAUDE" plugin update "$PLUGIN" >/dev/null 2>&1; then
        printf '✓ Claude Code: already installed, now the newest. Start a new session\n' >> "$RESULTS"
      else
        printf '✗ Claude Code: the plugin could not be updated. %s\n' "$MANUAL" >> "$RESULTS"
      fi
    elif "$CLAUDE" plugin install "$PLUGIN" >/dev/null 2>&1; then
      printf '✓ Claude Code: installed. Start a new session and ask for a workflow. If it asks you to sign in: type /mcp, choose browser-workflow, then Authenticate\n' >> "$RESULTS"
    else
      printf '✗ Claude Code: the plugin could not be installed. %s\n' "$MANUAL" >> "$RESULTS"
    fi
    # The plugin under its old name goes once the new one is in: both at once would start the app twice.
    if [ "$HAS_OLD" = 1 ] && "$CLAUDE" plugin list 2>/dev/null | grep -q " $PLUGIN"; then
      "$CLAUDE" plugin uninstall "$OLD_PLUGIN" >/dev/null 2>&1 || true
      rm -rf "$HOME"/.claude/plugins/data/browser-workflow-bridge*
    fi
  fi
fi

if [ "$REMOVE" = 1 ]; then
  stop_app; sleep 1
  rm -rf "$HOME/.browser-workflow-chatgpt" "$HOME/.browser-workflow-antigravity"
  # With the Claude app left as it is, the Node.js stays: running this again needs it to take the app out of Claude.
  if [ -d "$OWN_NODE" ] && [ -z "$CLAUDE_OPEN" ]; then rm -rf "$OWN_NODE"; printf '✓ The Node.js downloaded for the app: removed\n' >> "$RESULTS"; fi
fi

# ---- what happened ----------------------------------------------------------------------------
STEP="finishing"
say ""
if [ ! -s "$RESULTS" ]; then
  if [ "$REMOVE" = 1 ]; then say "Nothing of Browser Workflow was found on this computer."; else say "Nothing was installed."; fi
else
  if [ "$USE_COLOR" = 1 ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      case "$line" in
        ✓*)
          rest="${line#✓ }"
          status="$(printf '%s' "$rest" | sed -E 's/\. .*//')"
          printf '%s✓%s %s\n' "$C_BOLD$C_GREEN" "$C_RESET" "$status"
          ;;
        \!*)
          rest="${line#! }"
          printf '%s!%s %s\n' "$C_BOLD$C_YELLOW" "$C_RESET" "$rest"
          ;;
        ✗*)
          rest="${line#✗ }"
          printf '%s✗%s %s\n' "$C_BOLD$C_RED" "$C_RESET" "$rest"
          ;;
        *)
          printf '%s\n' "$line"
          ;;
      esac
    done < "$RESULTS"
  else
    cat "$RESULTS"
  fi
  cat "$RESULTS" >> "$LOG"
  if [ "$REMOVE" = 1 ]; then
    say ""
    if [ -n "$CLAUDE_OPEN" ]; then
      if [ "$USE_COLOR" = 1 ]; then
        printf '%s👉%s Browser Workflow is off this computer, except in the Claude app: %squit it completely and run the remove command again.%s\n' \
          "$C_BOLD$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
        printf 'Browser Workflow is off this computer, except in the Claude app: quit it completely and run the remove command again.\n' >> "$LOG"
      else
        say "Browser Workflow is off this computer, except in the Claude app: quit it completely and run the remove command again."
      fi
    else
      if [ "$USE_COLOR" = 1 ]; then
        printf '%s👉%s %sBrowser Workflow has been removed.%s Restart your AI app (ChatGPT / Claude) to finish.\n' \
          "$C_BOLD$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
        printf 'Browser Workflow has been removed. Restart your AI app (ChatGPT / Claude) to finish.\n' >> "$LOG"
      else
        say "Browser Workflow is off this computer. To start again, run the install command."
      fi
    fi
  elif grep -q '^✓' "$RESULTS"; then
    say ""
    if [ "$USE_COLOR" = 1 ]; then
      printf '%s👉%s %sRestart your AI app (ChatGPT / Claude), then try asking:%s\n' "$C_BOLD$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
      printf '   "Build a workflow to open google.com and search for iPhone"\n'
      printf 'Restart your AI app (ChatGPT / Claude), then try asking: "Build a workflow to open google.com and search for iPhone"\n' >> "$LOG"
    else
      say "Restart your AI app (ChatGPT / Claude), then try asking:"
      say '   "Build a workflow to open google.com and search for iPhone"'
    fi
  fi
fi
FAILED=0
grep -q '^✗' "$RESULTS" && FAILED=1
[ "$REMOVE" = 0 ] && ! grep -q '^✓' "$RESULTS" && FAILED=1
if [ "$FAILED" = 1 ]; then WHY="$(grep '^✗' "$RESULTS" | head -1)"; WHY="${WHY:-nothing was installed}"; fi
exit "$FAILED"
