#!/usr/bin/env bash
# Task 664 — rewrite permissions.allow:["*"] -> [] in place on existing
# installs. Claude Code >= 2.1.167 rejects "*" in allow rules and renders a
# blocking "Settings Warning" screen that, under --remote-control in a PTY,
# no operator dismisses — the stdout bind banner never prints and every
# rc-spawn times out. defaultMode:"bypassPermissions" (preserved) already
# carries the Stage-1 short-circuit, so the wildcard was always redundant.
#
# Targets the brand-scoped settings file and every account-scoped one.
# jq + atomic temp-write + rename. Idempotent: a file without "*" is left
# untouched and re-running is a no-op. One auditable line per file; file
# contents are never echoed.
#
# Usage: backfill-bypass-permissions.sh [INSTALL_DIR]
#   INSTALL_DIR defaults to $HOME/.maxy-code. Pass e.g. $HOME/.realagent-code
#   or $HOME/.sitedesk-code for other brands.
set -euo pipefail

INSTALL_DIR="${1:-$HOME/.maxy-code}"
BRAND_SETTINGS="$INSTALL_DIR/.claude/settings.json"

rewrite_one() {
  local f="$1"
  if [ ! -f "$f" ]; then
    echo "[backfill-664] file=$f status=absent"
    return 0
  fi
  if ! jq -e '.permissions' "$f" >/dev/null 2>&1; then
    echo "[backfill-664] file=$f status=no-permissions"
    return 0
  fi
  if jq -e '(.permissions.allow // []) | index("*")' "$f" >/dev/null 2>&1; then
    local tmp="$f.task664.tmp"
    # Guard the rewrite inside the `if` so a jq/mv failure (e.g. the file
    # changed under us, or a full disk) logs status=rewrite-failed and the
    # loop moves on, instead of `set -e` aborting the whole run and silently
    # leaving the remaining accounts on the broken allow:["*"]. The temp is
    # cleaned up on failure so no `.task664.tmp` is left behind.
    if jq '.permissions.allow = []' "$f" > "$tmp" && mv "$tmp" "$f"; then
      echo "[backfill-664] file=$f status=updated"
    else
      rm -f "$tmp"
      echo "[backfill-664] file=$f status=rewrite-failed" >&2
      return 0
    fi
  else
    echo "[backfill-664] file=$f status=already-set"
  fi
}

rewrite_one "$BRAND_SETTINGS"

if [ -d "$INSTALL_DIR/data/accounts" ]; then
  for acct in "$INSTALL_DIR"/data/accounts/*/.claude/settings.json; do
    [ -e "$acct" ] || continue
    rewrite_one "$acct"
  done
fi
