#!/usr/bin/env bash
# Monoceros devcontainer feature: claude-code.
#
# Installs the Anthropic Claude Code CLI globally via the npm registry.
# Login state lives at /home/node/.claude, which Monoceros bind-mounts
# from <container-dir>/home/.claude on the host so it survives apply
# rebuilds.
#
# If the optional `apiKey` option was passed in the container yml (or
# inherited from monoceros-config.yml defaults.features), this script
# writes a profile.d snippet that exports ANTHROPIC_API_KEY for every
# shell — Claude Code picks that up and skips the OAuth flow.

set -euo pipefail

VERSION="${VERSION:-latest}"
APIKEY="${APIKEY:-}"

echo "[claude-code] installing @anthropic-ai/claude-code@${VERSION} (as node)"

# Install as the non-root `node` user, NOT root (the feature install
# script itself runs as root). The base image's npm global prefix
# (/usr/local/share/npm-global) is owned by `node`, so installing as
# node leaves the Claude package files node-owned too. That is exactly
# what lets Claude's runtime self-updater write to them and keep itself
# current between Monoceros `upgrade`s. Installing as root drops
# root-owned files into that prefix that the non-root runtime user can
# never overwrite — the perpetual "Auto-update failed: no write
# permission to npm prefix" nag, frozen at the build-time version. See
# ADR 0018.
runuser -u node -- bash -lc \
  "npm install -g --no-audit --no-fund '@anthropic-ai/claude-code@${VERSION}'"

runuser -u node -- bash -lc 'claude --version' >/dev/null 2>&1 || {
  echo "[claude-code] ERROR: install completed but \`claude\` is not on PATH" >&2
  exit 1
}

# When an API key is configured, drop a profile.d snippet so every
# login shell exports it. We deliberately don't use containerEnv: the
# value would land in /proc/<pid>/environ of every process; the
# profile.d route at least keeps it out of non-shell process env when
# the container starts services directly.
if [ -n "${APIKEY}" ]; then
  cat >/etc/profile.d/claude-code-apikey.sh <<EOF
# Auto-generated by the Monoceros claude-code feature. Sets
# ANTHROPIC_API_KEY so Claude Code uses API auth instead of OAuth.
export ANTHROPIC_API_KEY='${APIKEY}'
EOF
  chmod 0644 /etc/profile.d/claude-code-apikey.sh
  echo "[claude-code] API key mode: ANTHROPIC_API_KEY wired via /etc/profile.d/"
else
  echo "[claude-code] subscription/OAuth mode: run \`claude\` once interactively to log in"
fi

echo "[claude-code] done"
