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

PROFILE_NAME="opencode-tinfoil"
SANDBOX_CONFIG_DIR="${HOME}/.config/opencode-sandbox/opencode"
SANDBOX_STATE_HOME="${HOME}/.local/state/opencode-sandbox"
SANDBOX_STATE_DIR="${SANDBOX_STATE_HOME}/opencode"
ACTIVE_DIR="${SANDBOX_STATE_HOME}/active"
SERVICE_STATE="${SANDBOX_STATE_DIR}/service.json"
REAL_CONFIG_DIR="${HOME}/.config/opencode"
SANDBOX_SERVICE_PORT=49376

# Resolve this script's own path, following symlinks so we can skip ourselves
# when scanning PATH for the real OpenCode binary.
self_path() {
  local src="${BASH_SOURCE[0]}" dir
  while [ -L "$src" ]; do
    dir="$(cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd)"
    src="$(readlink "$src")"
    case "$src" in
      /*) ;;
      *) src="${dir}/${src}" ;;
    esac
  done
  printf '%s/%s\n' "$(cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd)" "$(basename "$src")"
}

SELF="$(self_path)"

find_real_opencode() {
  local d c resolved
  local IFS=:
  for d in $PATH; do
    [ -n "$d" ] || continue
    for c in "$d/opencode" "$d/opencode.exe"; do
      [ -f "$c" ] && [ -x "$c" ] || continue
      resolved="$(cd -P "$(dirname "$c")" >/dev/null 2>&1 && pwd)/$(basename "$c")"
      if [ "$resolved" != "$SELF" ]; then
        printf '%s\n' "$c"
        return 0
      fi
    done
  done
  return 1
}

# Read the PID of the sandboxed background service from its state file.
sandbox_service_pid() {
  [ -f "${SERVICE_STATE}" ] || return 1
  sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "${SERVICE_STATE}" | head -n 1
}

# Stop the sandboxed background service. OpenCode spawns it detached, so it
# would otherwise outlive the nono supervisor (and lose the nono proxy).
stop_sandbox_service() {
  local pid cmd i
  pid="$(sandbox_service_pid || true)"
  if [ -z "${pid}" ] || ! kill -0 "${pid}" 2>/dev/null; then
    rm -f "${SERVICE_STATE}"
    return 0
  fi

  cmd="$(ps -p "${pid}" -o command= 2>/dev/null || true)"
  case "${cmd}" in
    *opencode*serve*--service*) ;;
    *) rm -f "${SERVICE_STATE}"; return 0 ;;
  esac

  # On Linux, make sure this is our sandbox service and not an unrelated
  # OpenCode service whose PID happened to be reused.
  if [ -r "/proc/${pid}/environ" ]; then
    if ! tr '\0' '\n' < "/proc/${pid}/environ" 2>/dev/null | grep -qF "OPENCODE_CONFIG_DIR=${SANDBOX_CONFIG_DIR}"; then
      if ! tr '\0' '\n' < "/proc/${pid}/environ" 2>/dev/null | grep -qF "XDG_STATE_HOME=${SANDBOX_STATE_HOME}"; then
        rm -f "${SERVICE_STATE}"
        return 0
      fi
    fi
  fi

  kill -TERM "${pid}" 2>/dev/null || true
  i=0
  while [ "${i}" -lt 10 ] && kill -0 "${pid}" 2>/dev/null; do
    sleep 0.2
    i=$((i + 1))
  done
  kill -KILL "${pid}" 2>/dev/null || true
  rm -f "${SERVICE_STATE}"
}

prune_active() {
  local f pid
  [ -d "${ACTIVE_DIR}" ] || return 0
  for f in "${ACTIVE_DIR}"/*; do
    [ -e "${f}" ] || continue
    pid="$(basename "${f}")"
    if ! kill -0 "${pid}" 2>/dev/null; then
      rm -f "${f}"
    fi
  done
}

active_count() {
  local f n=0
  [ -d "${ACTIVE_DIR}" ] || { echo 0; return; }
  for f in "${ACTIVE_DIR}"/*; do
    [ -e "${f}" ] || continue
    n=$((n + 1))
  done
  echo "${n}"
}

CLEANED=0
cleanup() {
  [ "${CLEANED}" -eq 1 ] && return 0
  CLEANED=1
  rm -f "${ACTIVE_DIR}/$$"
  prune_active
  # Stop the service once the last sandboxed instance exits. Its nono proxy
  # belongs to that instance's supervisor, so leaving it behind would leave a
  # service that can no longer reach the network.
  if [ "$(active_count)" -eq 0 ]; then
    stop_sandbox_service
  fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP

if ! command -v nono >/dev/null 2>&1; then
  echo "Error: nono not found in PATH. Install it first, e.g. 'brew install nono'." >&2
  exit 1
fi

REAL_OPENCODE="$(find_real_opencode || true)"
if [ -z "${REAL_OPENCODE}" ]; then
  echo "Error: real opencode binary not found in PATH (excluding this wrapper)." >&2
  exit 1
fi

# OpenCode v2 runs a background service. Give the sandbox its own config and
# state directories so it starts a dedicated service instead of discovering a
# host service running outside the sandbox.
mkdir -p "${SANDBOX_CONFIG_DIR}" "${SANDBOX_STATE_DIR}" "${ACTIVE_DIR}"

# Mirror the user's real config into the sandbox config dir, but never copy
# service.json: that file pins the sandbox service port.
if [ -d "${REAL_CONFIG_DIR}" ]; then
  shopt -s dotglob nullglob
  for entry in "${REAL_CONFIG_DIR}"/*; do
    name="$(basename "${entry}")"
    [ "${name}" = "service.json" ] && continue
    dest="${SANDBOX_CONFIG_DIR}/${name}"
    if [ -L "${dest}" ]; then
      rm -f "${dest}"
    fi
    if [ ! -e "${dest}" ]; then
      ln -s "${entry}" "${dest}"
    fi
  done
  shopt -u dotglob nullglob
fi

if [ ! -f "${SANDBOX_CONFIG_DIR}/service.json" ]; then
  printf '{\n  "port": %s\n}\n' "${SANDBOX_SERVICE_PORT}" > "${SANDBOX_CONFIG_DIR}/service.json"
  chmod 600 "${SANDBOX_CONFIG_DIR}/service.json"
fi

# If no other sandboxed OpenCode is running, clear out a service left behind by
# a previous session (for example after a SIGKILL) before starting a new one.
prune_active
if [ "$(active_count)" -eq 0 ]; then
  stop_sandbox_service
fi
: > "${ACTIVE_DIR}/$$"

nono run --profile "${PROFILE_NAME}" --allow-cwd -- "${REAL_OPENCODE}" "$@"
