#!/usr/bin/env bash
# Starts orcad for this boot (idempotent) and prints its recipe line:
# {"schemaVersion":1,"pairingCode":"orca://pair?...","projectRoot":"/vercel/sandbox/project"}
# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,
# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=<base64>` lines: org/personal/repo secrets for
# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).
# Never prints anything else on stdout's last line.
# With ORCA_READY_VIA=file it prints {"schemaVersion":1,"readyFile":"<path>"} instead and the control
# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.
# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,
# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the
# CONDUCTOR_* names imported Conductor scripts read.
set -euo pipefail
umask 077
ORCA_HOME=/opt/orca
STATE="$HOME/.orca-sandbox"
PROJECT=/vercel/sandbox/project
mkdir -p "$STATE"
exec 9>"$STATE/start.lock"
flock -w 60 9
# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole
# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.

# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,
# routine and phone sessions saw no repo. Register the workspace project at every start, in the
# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.
register_project() {
  [ -x "$ORCA_HOME/bin/orca" ] && [ -d "$PROJECT" ] || return 0
  local kind=()
  [ -e "$PROJECT/.git" ] || kind=(--kind folder)
  setsid "$ORCA_HOME/bin/orca" repo add --path "$PROJECT" "${kind[@]}" --json \
    >"$STATE/register-project.log" 2>&1 </dev/null 9>&- &
}

print_ready() {
  if [ "${ORCA_READY_VIA:-}" = file ]; then
    printf '{"schemaVersion":1,"readyFile":"%s"}\n' "$STATE/ready.json"
  else
    tail -n 1 "$STATE/ready.json"
  fi
}
# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.
redact_log() {
  local text kv value
  text="$(cat)"
  for kv in ${agent_env[@]+"${agent_env[@]}"}; do
    value="${kv#*=}"
    if [ "${#value}" -ge 8 ]; then
      text="${text//"$value"/[REDACTED]}"
    fi
  done
  printf '%s\n' "$text" | sed -E \
    -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \
    -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \
    -e 's#eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \
    -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\1: [REDACTED]#g'
}

node="$(find "$ORCA_HOME/runtime/runtimes" -type f -name node | head -n 1)"

# Share-link proxy (port 6769): answers only requests the control plane signed with this session's
# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so
# it never appears in any argv or in the proxy's /proc/<pid>/environ.
start_share_proxy() {
  [ -n "${ORCA_SHARE_PROXY_KEY:-}" ] && [ -x "$ORCA_HOME/bin/orca-share-proxy" ] || return 0
  if [ "$(cat "$STATE/share-proxy.boot" 2>/dev/null || true)" = "$boot_id" ] \
    && kill -0 "$(cat "$STATE/share-proxy.pid" 2>/dev/null || echo 0)" 2>/dev/null; then
    return 0
  fi
  printf '%s' "$ORCA_SHARE_PROXY_KEY" | env -i HOME="$HOME" LANG=C.UTF-8 PATH=/usr/bin:/bin \
    setsid "$node" "$ORCA_HOME/bin/orca-share-proxy" >"$STATE/share-proxy.log" 2>&1 9>&- &
  echo $! >"$STATE/share-proxy.pid"
  printf '%s' "$boot_id" >"$STATE/share-proxy.boot"
}

boot_id="$(cat /proc/sys/kernel/random/boot_id)"
start_share_proxy
unset ORCA_SHARE_PROXY_KEY
if [ "$(cat "$STATE/boot-id" 2>/dev/null || true)" = "$boot_id" ] && [ -s "$STATE/ready.json" ] \
  && kill -0 "$(cat "$STATE/orcad.pid" 2>/dev/null || echo 0)" 2>/dev/null; then
  print_ready
  exit 0
fi
# Resume = reboot from disk: locks and pids from the previous session name dead processes.
rm -f "$STATE/ready.json" "$STATE/orcad.pid"
printf '%s' "$boot_id" >"$STATE/boot-id"

if [ -n "${ORCA_GIT_EXTRAHEADER:-}" ]; then
  # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.
  git config --global http.https://github.com/.extraheader "$ORCA_GIT_EXTRAHEADER"
fi
# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.
git config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'
git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'
# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.
clone_pid=''
if [ ! -d "$PROJECT" ]; then
  mkdir -p "$PROJECT"
  if [ -n "${ORCA_REPO_URL:-}" ]; then
    git clone --quiet ${ORCA_REPO_REF:+--branch "$ORCA_REPO_REF"} -- "$ORCA_REPO_URL" "$PROJECT" 2>"$STATE/clone.log" 9>&- &
    clone_pid=$!
  fi
fi

# The clone may still be running here, so the name comes from the URL; the default branch is
# filled in lazily by the session-env shell hook once the clone exists.
if [ -n "${ORCA_REPO_URL:-}" ]; then
  workspace_name="$(basename "${ORCA_REPO_URL%/}" .git)"
else
  workspace_name="$(basename "$(git -C "$PROJECT" remote get-url origin 2>/dev/null || echo "$PROJECT")" .git)"
fi
# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).
managed_env=(
  ORCA_IS_CLOUD=1
  ORCA_ROOT_PATH="$PROJECT" ORCA_WORKTREE_PATH="$PROJECT" ORCA_WORKSPACE_PATH="$PROJECT"
  ORCA_WORKSPACE_NAME="$workspace_name" ORCA_PORT=3000
  CONDUCTOR_IS_CLOUD=1
  CONDUCTOR_ROOT_PATH="$PROJECT" CONDUCTOR_WORKSPACE_PATH="$PROJECT"
  CONDUCTOR_WORKSPACE_NAME="$workspace_name" CONDUCTOR_PORT=3000
)

agent_env=()
if command -v google-chrome >/dev/null; then
  # Orca's browser automation and agent browser tools use the image's headless Chrome.
  agent_env+=("ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)")
fi
if [ -n "${ORCA_GITHUB_PLACEHOLDER:-}" ]; then
  # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.
  agent_env+=("GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER" "GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER")
fi

secret_names=()
if [ -n "${ORCA_SECRET_ENV:-}" ]; then
  # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read
  # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.
  # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.
  while IFS= read -r line; do
    name="${line%%=*}" b64="${line#*=}" # not IFS='=': read would strip base64 padding
    case "$name" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac
    agent_env+=("$name=$(printf '%s' "$b64" | base64 -d)")
    secret_names+=("$name")
  done < <(printf '%s\n' "$ORCA_SECRET_ENV") # a pipe, not a here-string temp file
fi
# Always rewrite the file, so a resume with fewer secrets drops the old names too.
"$ORCA_HOME/bin/orca-sandbox-env" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2
unset ORCA_SECRET_ENV

# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:
# terminals need that node on PATH, not only orcad's bundled runtime.
system_node="$(command -v node 2>/dev/null || echo "$node")"
env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 TERM=xterm-256color \
  PATH="$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname "$system_node"):/usr/local/bin:/usr/bin:/bin" \
  ORCA_USER_DATA="$HOME/.orcad-data" ORCA_SANDBOX_ID="$ORCA_SANDBOX_ID" "${managed_env[@]}" \
  NODE_COMPILE_CACHE="$ORCA_HOME/compile-cache" \
  ORCA_SESSION_ENV_NAMES="${secret_names[*]}" "${agent_env[@]}" \
  setsid nohup "$node" "$ORCA_HOME/runtime/orcad/orcad-server.js" \
  --port 6768 --bind 0.0.0.0 --pairing-address "$ORCA_PUBLIC_WSS" \
  --recipe-json --project-root "$PROJECT" \
  >"$STATE/ready.json" 2>"$STATE/orcad.log" </dev/null 9>&- &
echo $! >"$STATE/orcad.pid"

# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.
"$ORCA_HOME/bin/orca-sshd" >/dev/null 2>"$STATE/sshd-start.err" || true

for _ in $(seq 1 1200); do
  if grep -q '"pairingCode"' "$STATE/ready.json" 2>/dev/null; then
    if [ -n "$clone_pid" ] && ! wait "$clone_pid"; then
      echo 'repository clone failed' >&2
      tail -n 5 "$STATE/clone.log" | redact_log >&2
      exit 1
    fi
    register_project
    print_ready
    exit 0
  fi
  if ! kill -0 "$(cat "$STATE/orcad.pid")" 2>/dev/null; then
    echo 'orcad exited before ready' >&2
    tail -n 40 "$STATE/orcad.log" | redact_log >&2
    exit 1
  fi
  sleep 0.05
done
echo 'orcad start timed out' >&2
exit 1
