#!/usr/bin/env sh
set -eu

cd /

INSTALL_DIR="${FORGE_HOME:-/opt/forgecloud}"
APP_DIR="${FORGE_APP_DIR:-$INSTALL_DIR}"
DATA_DIR="$APP_DIR/data"
# Host helper families installed on image installs (FORGE_CONTROL_PLANE_HOST_ISOLATION_SPEC.md §5.2).
HOST_HELPER_FAMILIES="ingress self_update qualification inventory maintenance countersign migration_source"
# Root-only evacuation tunnel directories (host isolation spec §12.3 decision 2). Only the
# migration_source helper writes them; each tunnel process mounts its own directory read-only.
MIGRATION_TUNNEL_DIR="/etc/forgecloud/migration-tunnels"
# Root-owned ingress directory for the isolated layout (FORGE_CONTROL_PLANE_HOST_ISOLATION_SPEC.md
# §12.3 decision 4). forge-cloud never mounts it; only the ingress helper writes the live Caddyfile.
INGRESS_DIR="/etc/forgecloud/ingress"
# Operator security-key registry and countersign helper key (host isolation spec §12.3 decision 3).
# forge-cloud never mounts either. The countersign directory is world-traversable so the local Agent
# can read its public trust file; the helper key inside it is root-only.
OPERATOR_KEYS_DIR="/etc/forgecloud/operator-keys"
COUNTERSIGN_DIR="/etc/forge-countersign"
# Root-only reserve-slice requests (compute spec §25.1 decision 5). Only the maintenance helper writes
# slices.env; the root forge-reserve-slices script renders the slice units from it.
RESERVE_SLICE_DIR="/etc/forgecloud/reserve-slices"
# Whether forge-cloud, Caddy and BuildKit run in forge-control.slice (compute spec §25.1 decision 5). Set only
# by resolve_control_slice on each run, never recorded: a rerun with the slice absent writes compose without it.
CONTROL_SLICE_ASSIGNED="false"
CONTROL_SLICE_DETAIL=""
CONTROL_SLICE_CHANGED="false"
CONTROL_SLICE_UNIT_DIR="/etc/systemd/system"
INGRESS_LAYOUT="legacy"
# Whether forge-cloud may write .env (§12.3 decision 8). read_only mounts it read-only; recorded like the layout.
ENV_FILE_MODE="writable"
ENV_FILE_MODE_PATH="/etc/forgecloud/env-file-mode"
# The account forge-cloud runs as (§12.3 decision 5). root keeps every owner and mode exactly as before.
CONTROL_PLANE_USER="root"
CONTROL_PLANE_USER_PATH="/etc/forgecloud/control-plane-user"
CONTROL_PLANE_OWNERSHIP_MANIFEST="/etc/forgecloud/control-plane-ownership.manifest"
CP_UID=0
CP_GID=0
CP_REQUEST_DIR_MODE=0700
CP_READ_DIR_MODE=0700
CP_SHARED_FILE_MODE=0600
DOCKER_SOCKET_GID=""
# Whether forge-cloud gets the Docker socket (host isolation spec §6 Phase 9). mounted is today's
# layout; removed gives it no socket, no install-directory mount and a hardened container, and is
# written only after the root preflight finds nothing on the host that still needs the socket.
DOCKER_SOCKET_MODE="mounted"
DOCKER_SOCKET_MODE_PATH="/etc/forgecloud/control-plane-docker-socket"
# BuildKit (§12.3 decision 7): privileged_tcp is today's container; rootless_socket runs the owner-reviewed
# rootless image, pinned by digest, on a Unix socket only forge-cloud mounts. Recorded like the layout.
BUILDKIT_MODE="privileged_tcp"
BUILDKIT_MODE_PATH="/etc/forgecloud/buildkit-mode"
BUILDKIT_IMAGE=""
BUILDKIT_IMAGE_PATH="/etc/forgecloud/buildkit-image"
BUILDKIT_SOCKET_DIR="/var/lib/forgecloud/buildkit-socket"
# The rootless image runs as this uid; its socket directory is owned by it.
BUILDKIT_ROOTLESS_UID=1000
# Who may reach forge-cloud's port (§12.3 decision 6, option c). open is today's behaviour; caddy_only
# binds forge-cloud to loopback and a host firewall admits only root (Caddy, the helpers) and forge-cloud.
PORT_ACCESS="open"
PORT_ACCESS_PATH="/etc/forgecloud/control-plane-port-access"
# How the host mail scripts reach forge-cloud: tcp_loopback (today) or unix_socket.
MAIL_CALLBACK_TRANSPORT="tcp_loopback"
MAIL_CALLBACK_TRANSPORT_PATH="/etc/forgecloud/mail-callback-transport"
MAIL_CALLBACK_DIR="/var/lib/forgecloud/mail-callback"
MAIL_CALLBACK_GROUP="forge-mail-callback"
MAIL_CALLBACK_GID=""
INSTALL_MODE="${FORGE_INSTALL_MODE:-image}"
REPO_URL="${FORGE_REPO_URL:-https://github.com/adeyomilawal/forge.git}"
REPO_BRANCH="${FORGE_REPO_BRANCH:-master}"
FORGE_IMAGE="${FORGE_IMAGE:-ghcr.io/adeyomilawal/forge:latest}"
FORGE_IMAGE_DIGEST=""
RAILPACK_VERSION="${RAILPACK_VERSION:-0.30.0}"
AUTO_UPDATE_ENABLED="${FORGE_AUTO_UPDATE_ENABLED:-false}"
AUTO_UPDATE_INTERVAL_MINUTES="${FORGE_AUTO_UPDATE_INTERVAL_MINUTES:-60}"
PORT="${FORGE_PORT:-4310}"
EMAIL_ENABLED="${FORGE_EMAIL_ENABLED:-false}"
EMAIL_INBOUND_ENABLED="${FORGE_EMAIL_INBOUND_ENABLED:-false}"
WEBSITE_HOSTNAMES="${FORGE_WEBSITE_HOSTNAMES:-}"
PRODUCT_DOMAIN="${FORGE_PRODUCT_DOMAIN:-}"
ADMIN_HOSTNAME="${FORGE_ADMIN_HOSTNAME:-}"
if [ -n "${FORGE_WEBSITE_STATIC_ENABLED:-}" ]; then
  WEBSITE_STATIC_ENABLED="$FORGE_WEBSITE_STATIC_ENABLED"
elif [ -n "$WEBSITE_HOSTNAMES$PRODUCT_DOMAIN" ]; then
  WEBSITE_STATIC_ENABLED="true"
else
  WEBSITE_STATIC_ENABLED="false"
fi
if [ -n "${FORGE_WEBSITE_AUTO_UPDATE_ENABLED:-}" ]; then
  WEBSITE_AUTO_UPDATE_ENABLED="$FORGE_WEBSITE_AUTO_UPDATE_ENABLED"
elif [ "$WEBSITE_STATIC_ENABLED" = "true" ]; then
  WEBSITE_AUTO_UPDATE_ENABLED="true"
else
  WEBSITE_AUTO_UPDATE_ENABLED="false"
fi
WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES="${FORGE_WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES:-30}"
WEBSITE_UPDATE_ROOT_DIR="${FORGE_WEBSITE_UPDATE_ROOT_DIR:-website}"

if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  if ! command -v sudo >/dev/null 2>&1; then
    echo "sudo is required when installing as a non-root user."
    exit 1
  fi
  SUDO="sudo"
fi

say() {
  printf '%s\n' "$*"
}

fail() {
  say "Error: $*"
  exit 1
}

normalize_install_mode() {
  INSTALL_MODE="$(printf '%s' "$INSTALL_MODE" | tr '[:upper:]' '[:lower:]')"
  case "$INSTALL_MODE" in
    image|docker|docker-image)
      INSTALL_MODE="image"
      ;;
    git|source)
      INSTALL_MODE="git"
      ;;
    *)
      fail "FORGE_INSTALL_MODE must be image or git."
      ;;
  esac
}

is_image_mode() {
  [ "$INSTALL_MODE" = "image" ]
}

require_linux() {
  [ "$(uname -s)" = "Linux" ] || fail "Forge's VPS installer currently supports Linux hosts."

  if [ -r /etc/os-release ]; then
    # shellcheck disable=SC1091
    . /etc/os-release
    case "${ID:-}" in
      ubuntu|debian) ;;
      *)
        say "Warning: this installer is tuned for Ubuntu/Debian. Continuing on ${PRETTY_NAME:-unknown Linux}."
        ;;
    esac
  fi
}

require_apt() {
  command -v apt-get >/dev/null 2>&1 || fail "apt-get was not found. The installer currently supports Ubuntu/Debian hosts."
}

install_base_packages() {
  require_apt
  say "Installing base packages..."
  $SUDO apt-get update
  packages="age ca-certificates curl git openssl util-linux"
  if ! is_image_mode; then
    packages="$packages build-essential python3"
  fi
  $SUDO apt-get install -y $packages
}

node_major_version() {
  node -p "process.versions.node.split('.')[0]" 2>/dev/null || printf '0\n'
}

install_node() {
  if command -v node >/dev/null 2>&1 && [ "$(node_major_version)" -ge 22 ]; then
    return
  fi

  say "Installing Node.js 22..."
  curl -fsSL https://deb.nodesource.com/setup_22.x | $SUDO bash -
  $SUDO apt-get install -y nodejs
}

install_docker() {
  if command -v docker >/dev/null 2>&1; then
    if command -v systemctl >/dev/null 2>&1; then
      $SUDO systemctl enable --now docker >/dev/null 2>&1 || true
    fi
    return
  fi

  say "Installing Docker..."
  $SUDO apt-get install -y docker.io
  if command -v systemctl >/dev/null 2>&1; then
    $SUDO systemctl enable --now docker >/dev/null 2>&1 || true
  fi
}

install_compose_package() {
  for package_name in docker-compose-plugin docker-compose-v2; do
    if apt-cache show "$package_name" >/dev/null 2>&1; then
      $SUDO apt-get install -y "$package_name"
      return
    fi
  done

  fail "Docker Compose v2 was not found in apt. Enable Ubuntu universe or Docker's apt repository, then rerun this installer."
}

require_compose() {
  if $SUDO docker compose version >/dev/null 2>&1; then
    return
  fi

  say "Installing Docker Compose plugin..."
  install_compose_package

  $SUDO docker compose version >/dev/null 2>&1 || fail "Docker Compose plugin is still unavailable."
}

docker_bin() {
  command -v docker 2>/dev/null || fail "docker was not found after installation."
}

install_railpack() {
  if command -v railpack >/dev/null 2>&1; then
    return
  fi

  say "Installing Railpack..."
  curl -fsSL https://railpack.com/install.sh | $SUDO env RAILPACK_VERSION="$RAILPACK_VERSION" bash -s -- --bin-dir /usr/local/bin
}

random_secret() {
  if command -v openssl >/dev/null 2>&1; then
    openssl rand -base64 32 | tr '+/' '-_' | tr -d '='
    return
  fi
  dd if=/dev/urandom bs=32 count=1 2>/dev/null | od -An -tx1 | tr -d ' \n'
}

detect_public_url() {
  if [ -n "${FORGE_PUBLIC_URL:-}" ]; then
    printf '%s\n' "$FORGE_PUBLIC_URL"
    return
  fi

  public_ip=""
  if command -v curl >/dev/null 2>&1; then
    public_ip="$(curl -fsSL --max-time 4 https://api.ipify.org 2>/dev/null || true)"
  fi
  if [ -z "$public_ip" ] && command -v hostname >/dev/null 2>&1; then
    public_ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
  fi
  if [ -z "$public_ip" ]; then
    public_ip="localhost"
  fi

  printf 'http://%s:%s\n' "$public_ip" "$PORT"
}

get_env_value() {
  env_file="$1"
  key="$2"
  [ -f "$env_file" ] || return 0
  value="$(grep "^$key=" "$env_file" 2>/dev/null | tail -n 1 | cut -d= -f2- || true)"
  printf '%s' "$value" | sed "s/^[\"']//;s/[\"']$//"
}

prepare_install_dir() {
  if [ -e "$INSTALL_DIR" ] && [ ! -d "$INSTALL_DIR" ]; then
    fail "$INSTALL_DIR exists and is not a directory."
  fi

  if [ ! -e "$INSTALL_DIR" ]; then
    say "Creating $INSTALL_DIR..."
    $SUDO mkdir -p "$INSTALL_DIR"
    if [ -n "$SUDO" ]; then
      $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
    fi
  fi
}

clone_or_update_repo() {
  prepare_install_dir

  if [ -d "$INSTALL_DIR/.git" ]; then
    say "Updating Forge source..."
    git -C "$INSTALL_DIR" fetch origin "$REPO_BRANCH"
    git -C "$INSTALL_DIR" checkout "$REPO_BRANCH"
    git -C "$INSTALL_DIR" pull --ff-only origin "$REPO_BRANCH"
  else
    if [ -n "$(ls -A "$INSTALL_DIR" 2>/dev/null)" ]; then
      fail "$INSTALL_DIR exists but is not an empty directory or Git checkout. Move it aside and rerun the installer."
    fi

    say "Cloning Forge..."
    git clone --branch "$REPO_BRANCH" --single-branch "$REPO_URL" "$INSTALL_DIR"
  fi

  if [ ! -f "$APP_DIR/package.json" ] && [ -f "$INSTALL_DIR/deploy/package.json" ]; then
    APP_DIR="$INSTALL_DIR/deploy"
    DATA_DIR="$APP_DIR/data"
  fi

  [ -f "$APP_DIR/package.json" ] || fail "$APP_DIR/package.json was not found after clone. Check FORGE_REPO_URL, FORGE_APP_DIR, and FORGE_REPO_BRANCH."
  mkdir -p "$DATA_DIR"
}

prepare_image_install() {
  prepare_install_dir
  APP_DIR="$INSTALL_DIR"
  DATA_DIR="$APP_DIR/data"
  mkdir -p "$DATA_DIR"
  image_to_install="$(get_env_value "$APP_DIR/.env" FORGE_IMAGE)"
  if [ -z "$image_to_install" ]; then
    image_to_install="$FORGE_IMAGE"
  fi
  $SUDO docker image pull "$image_to_install" >/dev/null
  FORGE_IMAGE_DIGEST="$($SUDO docker image inspect --format '{{.Id}}' "$image_to_install")"
  printf '%s' "$FORGE_IMAGE_DIGEST" | grep -Eq '^sha256:[a-f0-9]{64}$' || fail "Forge image does not expose an exact OCI image digest."
}

write_env_file() {
  env_file="$APP_DIR/.env"
  operator_bootstrap_token_generated=false
  secret_key="$(get_env_value "$env_file" FORGE_SECRET_KEY)"
  operator_bootstrap_token="$(get_env_value "$env_file" FORGE_OPERATOR_BOOTSTRAP_TOKEN)"
  database_backup_key="$(get_env_value "$env_file" FORGE_DATABASE_BACKUP_KEY)"
  database_backup_keyring="$(get_env_value "$env_file" FORGE_DATABASE_BACKUP_KEYRING)"
  public_url="$(get_env_value "$env_file" PUBLIC_URL)"
  control_plane_hostname="$(get_env_value "$env_file" CONTROL_PLANE_HOSTNAME)"
  admin_hostname="$(get_env_value "$env_file" FORGE_ADMIN_HOSTNAME)"
  website_hostnames="$(get_env_value "$env_file" FORGE_WEBSITE_HOSTNAMES)"
  product_domain="$(get_env_value "$env_file" FORGE_PRODUCT_DOMAIN)"
  forge_image="$(get_env_value "$env_file" FORGE_IMAGE)"
  auto_update_enabled="$(get_env_value "$env_file" FORGE_AUTO_UPDATE_ENABLED)"
  auto_update_interval_minutes="$(get_env_value "$env_file" FORGE_AUTO_UPDATE_INTERVAL_MINUTES)"
  website_static_enabled="$(get_env_value "$env_file" FORGE_WEBSITE_STATIC_ENABLED)"
  website_auto_update_enabled="$(get_env_value "$env_file" FORGE_WEBSITE_AUTO_UPDATE_ENABLED)"
  website_auto_update_interval_minutes="$(get_env_value "$env_file" FORGE_WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES)"
  website_update_root_dir="$(get_env_value "$env_file" FORGE_WEBSITE_UPDATE_ROOT_DIR)"
  email_enabled="$(get_env_value "$env_file" FORGE_EMAIL_ENABLED)"
  email_inbound_enabled="$(get_env_value "$env_file" FORGE_EMAIL_INBOUND_ENABLED)"

  if [ -z "$secret_key" ]; then
    secret_key="$(random_secret)"
  fi
  if [ -z "$operator_bootstrap_token" ]; then
    operator_bootstrap_token="$(random_secret)"
    operator_bootstrap_token_generated=true
  fi
  if [ -z "$database_backup_key" ]; then
    database_backup_key="$(random_secret)"
  fi
  if [ -z "$public_url" ]; then
    public_url="$(detect_public_url)"
  fi
  if [ -z "$website_hostnames" ]; then
    website_hostnames="$WEBSITE_HOSTNAMES"
  fi
  if [ -z "$product_domain" ]; then
    product_domain="$PRODUCT_DOMAIN"
  fi
  if [ -z "$admin_hostname" ]; then
    admin_hostname="$ADMIN_HOSTNAME"
  fi
  if [ -z "$admin_hostname" ] && [ -n "$product_domain" ]; then
    admin_hostname="admin.$product_domain"
  fi
  if [ -z "$forge_image" ]; then
    forge_image="$FORGE_IMAGE"
  fi
  if [ -z "$auto_update_enabled" ]; then
    auto_update_enabled="$AUTO_UPDATE_ENABLED"
  fi
  if [ -z "$auto_update_interval_minutes" ]; then
    auto_update_interval_minutes="$AUTO_UPDATE_INTERVAL_MINUTES"
  fi
  if [ -z "$website_static_enabled" ]; then
    website_static_enabled="$WEBSITE_STATIC_ENABLED"
  fi
  if [ -z "$website_auto_update_enabled" ]; then
    website_auto_update_enabled="$WEBSITE_AUTO_UPDATE_ENABLED"
  fi
  if [ -z "$website_auto_update_interval_minutes" ]; then
    website_auto_update_interval_minutes="$WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES"
  fi
  if [ -z "$website_update_root_dir" ]; then
    website_update_root_dir="$WEBSITE_UPDATE_ROOT_DIR"
  fi
  if [ -z "$email_enabled" ]; then
    email_enabled="$EMAIL_ENABLED"
  fi
  if [ -z "$email_inbound_enabled" ]; then
    email_inbound_enabled="$EMAIL_INBOUND_ENABLED"
  fi

  tmp_file="$(mktemp)"
  if [ -f "$env_file" ]; then
    grep -v -E '^(FORGE_INSTALL_MODE|FORGE_INSTALL_DIR|FORGE_ENV_PATH|FORGE_REPO_URL|FORGE_REPO_BRANCH|FORGE_IMAGE|FORGE_IMAGE_DIGEST|FORGE_IMAGE_UPDATE_CMD|FORGE_COMMIT_SHA|FORGE_COMPOSE_FILE|FORGE_UPDATE_REPO_URL|FORGE_UPDATE_BRANCH|FORGE_UPDATE_RESTART_CMD|FORGE_AUTO_UPDATE_ENABLED|FORGE_AUTO_UPDATE_INTERVAL_MINUTES|FORGE_WEBSITE_STATIC_ENABLED|FORGE_WEBSITE_SERVE_DIR|FORGE_WEBSITE_CADDY_SERVE_DIR|FORGE_WEBSITE_UPDATE_REPO_URL|FORGE_WEBSITE_UPDATE_BRANCH|FORGE_WEBSITE_UPDATE_ROOT_DIR|FORGE_WEBSITE_AUTO_UPDATE_ENABLED|FORGE_WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES|FORGE_SECRET_KEY|FORGE_OPERATOR_BOOTSTRAP_TOKEN|FORGE_DATABASE_BACKUP_KEY|FORGE_DATABASE_BACKUP_KEYRING|DATA_DIR|DEPLOY_DRY_RUN|CADDY_CONFIG_PATH|CADDY_DATA_DIR|CADDY_RELOAD_CMD|PORT|HOST|HOME|DOCKER_CONFIG|PUBLIC_URL|CONTROL_PLANE_HOSTNAME|FORGE_ADMIN_HOSTNAME|FORGE_WEBSITE_HOSTNAMES|FORGE_PRODUCT_DOMAIN|BUILDKIT_HOST|FORGE_RUNTIME_NETWORK|FORGE_EMAIL_ENABLED|FORGE_EMAIL_INBOUND_ENABLED)=' "$env_file" > "$tmp_file" || true
  else
    : > "$tmp_file"
  fi

  if is_image_mode; then
    cat >> "$tmp_file" <<EOF
FORGE_INSTALL_MODE=image
FORGE_INSTALL_DIR=$APP_DIR
FORGE_ENV_PATH=$APP_DIR/.env
FORGE_IMAGE=$forge_image
FORGE_IMAGE_DIGEST=$FORGE_IMAGE_DIGEST
FORGE_COMPOSE_FILE=$APP_DIR/compose.yml
FORGE_UPDATE_REPO_URL=$REPO_URL
FORGE_UPDATE_BRANCH=$REPO_BRANCH
FORGE_AUTO_UPDATE_ENABLED=$auto_update_enabled
FORGE_AUTO_UPDATE_INTERVAL_MINUTES=$auto_update_interval_minutes
FORGE_WEBSITE_STATIC_ENABLED=$website_static_enabled
FORGE_WEBSITE_SERVE_DIR=$DATA_DIR/website/current
FORGE_WEBSITE_CADDY_SERVE_DIR=/srv/deploy-data/website/current
FORGE_WEBSITE_UPDATE_REPO_URL=$REPO_URL
FORGE_WEBSITE_UPDATE_BRANCH=$REPO_BRANCH
FORGE_WEBSITE_UPDATE_ROOT_DIR=$website_update_root_dir
FORGE_WEBSITE_AUTO_UPDATE_ENABLED=$website_auto_update_enabled
FORGE_WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES=$website_auto_update_interval_minutes
FORGE_SECRET_KEY=$secret_key
FORGE_OPERATOR_BOOTSTRAP_TOKEN=$operator_bootstrap_token
DATA_DIR=$DATA_DIR
DEPLOY_DRY_RUN=false
CADDY_CONFIG_PATH=$DATA_DIR/Caddyfile
CADDY_DATA_DIR=/srv/deploy-data
CADDY_RELOAD_CMD=docker exec deploy-caddy caddy reload --config /srv/deploy-data/Caddyfile --adapter caddyfile
PORT=$PORT
HOST=0.0.0.0
HOME=$DATA_DIR/runtime-home
DOCKER_CONFIG=$DATA_DIR/docker-config
PUBLIC_URL=$public_url
BUILDKIT_HOST=tcp://127.0.0.1:1234
FORGE_RUNTIME_NETWORK=forge-runtime
FORGE_EMAIL_ENABLED=$email_enabled
FORGE_EMAIL_INBOUND_ENABLED=$email_inbound_enabled
EOF
  else
    cat >> "$tmp_file" <<EOF
FORGE_INSTALL_MODE=git
FORGE_INSTALL_DIR=$APP_DIR
FORGE_ENV_PATH=$APP_DIR/.env
FORGE_REPO_URL=$REPO_URL
FORGE_REPO_BRANCH=$REPO_BRANCH
FORGE_IMAGE=$forge_image
FORGE_COMPOSE_FILE=$APP_DIR/compose.yml
FORGE_UPDATE_REPO_URL=$REPO_URL
FORGE_UPDATE_BRANCH=$REPO_BRANCH
FORGE_UPDATE_RESTART_CMD=systemctl restart forge-cloud
FORGE_AUTO_UPDATE_ENABLED=$auto_update_enabled
FORGE_AUTO_UPDATE_INTERVAL_MINUTES=$auto_update_interval_minutes
FORGE_WEBSITE_STATIC_ENABLED=$website_static_enabled
FORGE_WEBSITE_SERVE_DIR=$DATA_DIR/website/current
FORGE_WEBSITE_CADDY_SERVE_DIR=/srv/deploy-data/website/current
FORGE_WEBSITE_UPDATE_REPO_URL=$REPO_URL
FORGE_WEBSITE_UPDATE_BRANCH=$REPO_BRANCH
FORGE_WEBSITE_UPDATE_ROOT_DIR=$website_update_root_dir
FORGE_WEBSITE_AUTO_UPDATE_ENABLED=$website_auto_update_enabled
FORGE_WEBSITE_AUTO_UPDATE_INTERVAL_MINUTES=$website_auto_update_interval_minutes
FORGE_SECRET_KEY=$secret_key
FORGE_OPERATOR_BOOTSTRAP_TOKEN=$operator_bootstrap_token
DATA_DIR=$DATA_DIR
DEPLOY_DRY_RUN=false
CADDY_CONFIG_PATH=$DATA_DIR/Caddyfile
CADDY_DATA_DIR=/srv/deploy-data
CADDY_RELOAD_CMD=docker exec deploy-caddy caddy reload --config /srv/deploy-data/Caddyfile --adapter caddyfile
PORT=$PORT
HOST=0.0.0.0
PUBLIC_URL=$public_url
BUILDKIT_HOST=tcp://127.0.0.1:1234
FORGE_RUNTIME_NETWORK=forge-runtime
FORGE_EMAIL_ENABLED=$email_enabled
FORGE_EMAIL_INBOUND_ENABLED=$email_inbound_enabled
EOF
  fi

  printf 'FORGE_DATABASE_BACKUP_KEY=%s\n' "$database_backup_key" >> "$tmp_file"
  if [ -n "$database_backup_keyring" ]; then
    printf 'FORGE_DATABASE_BACKUP_KEYRING=%s\n' "$database_backup_keyring" >> "$tmp_file"
  fi

  if [ -n "$control_plane_hostname" ]; then
    printf 'CONTROL_PLANE_HOSTNAME=%s\n' "$control_plane_hostname" >> "$tmp_file"
  fi
  if [ -n "$admin_hostname" ]; then
    printf 'FORGE_ADMIN_HOSTNAME=%s\n' "$admin_hostname" >> "$tmp_file"
  fi
  if [ -n "$website_hostnames" ]; then
    printf 'FORGE_WEBSITE_HOSTNAMES=%s\n' "$website_hostnames" >> "$tmp_file"
  fi
  if [ -n "$product_domain" ]; then
    printf 'FORGE_PRODUCT_DOMAIN=%s\n' "$product_domain" >> "$tmp_file"
  fi

  mv "$tmp_file" "$env_file"
  chmod 600 "$env_file"
}

resolve_ingress_layout() {
  # An explicit FORGE_INGRESS_LAYOUT wins; otherwise the layout recorded by an earlier run is kept,
  # so a plain rerun never changes Caddy. The isolated layout needs the image-mode ingress helper.
  requested="${FORGE_INGRESS_LAYOUT:-}"
  if [ -z "$requested" ] && [ -f "$INGRESS_DIR/layout" ]; then
    requested="$($SUDO cat "$INGRESS_DIR/layout")"
  fi
  case "${requested:-legacy}" in
    legacy) INGRESS_LAYOUT=legacy ;;
    isolated)
      is_image_mode || fail "FORGE_INGRESS_LAYOUT=isolated requires image mode and its root ingress helper."
      INGRESS_LAYOUT=isolated
      ;;
    *) fail "FORGE_INGRESS_LAYOUT must be legacy or isolated." ;;
  esac
}

resolve_env_file_mode() {
  # An explicit FORGE_ENV_FILE_MODE wins; otherwise the recorded mode is kept, so a plain rerun changes nothing.
  requested="${FORGE_ENV_FILE_MODE:-}"
  if [ -z "$requested" ] && [ -f "$ENV_FILE_MODE_PATH" ]; then
    requested="$($SUDO cat "$ENV_FILE_MODE_PATH")"
  fi
  case "${requested:-writable}" in
    writable) ENV_FILE_MODE=writable ;;
    read_only)
      is_image_mode || fail "FORGE_ENV_FILE_MODE=read_only requires image mode."
      ENV_FILE_MODE=read_only
      ;;
    *) fail "FORGE_ENV_FILE_MODE must be writable or read_only." ;;
  esac
}

record_env_file_mode() {
  if [ "$ENV_FILE_MODE" = "read_only" ] || $SUDO test -f "$ENV_FILE_MODE_PATH"; then
    # The same root-only directory as the runtime reconciler configuration; its mode is not loosened.
    $SUDO install -d -m 0700 -o root -g root "$(dirname "$ENV_FILE_MODE_PATH")"
    mode_tmp="$(mktemp)"
    printf '%s\n' "$ENV_FILE_MODE" > "$mode_tmp"
    $SUDO install -m 0644 -o root -g root "$mode_tmp" "$ENV_FILE_MODE_PATH"
    rm -f "$mode_tmp"
  fi
}

resolve_control_plane_user() {
  # An explicit FORGE_CONTROL_PLANE_USER wins; otherwise the recorded account is kept.
  requested="${FORGE_CONTROL_PLANE_USER:-}"
  if [ -z "$requested" ] && [ -f "$CONTROL_PLANE_USER_PATH" ]; then
    requested="$($SUDO cat "$CONTROL_PLANE_USER_PATH")"
  fi
  case "${requested:-root}" in
    root) CONTROL_PLANE_USER=root ;;
    forgecloud)
      is_image_mode || fail "FORGE_CONTROL_PLANE_USER=forgecloud requires image mode."
      # The root reconciler trusts only a root-owned .env, which a non-root forge-cloud cannot write.
      [ "$ENV_FILE_MODE" = "read_only" ] || fail "FORGE_CONTROL_PLANE_USER=forgecloud requires FORGE_ENV_FILE_MODE=read_only."
      CONTROL_PLANE_USER=forgecloud
      ;;
    *) fail "FORGE_CONTROL_PLANE_USER must be root or forgecloud." ;;
  esac
}

resolve_control_plane_ids() {
  [ "$CONTROL_PLANE_USER" = "forgecloud" ] || return 0
  CP_UID="$(id -u forgecloud)"
  CP_GID="$(id -g forgecloud)"
  [ "$CP_UID" != "0" ] && [ "$CP_GID" != "0" ] || fail "The forgecloud account must not be uid or gid 0."
  CP_REQUEST_DIR_MODE=1770
  CP_READ_DIR_MODE=0750
  CP_SHARED_FILE_MODE=0640
  # While the socket is mounted forge-cloud still needs it, so this account is not yet a root boundary.
  if [ "$DOCKER_SOCKET_MODE" = "mounted" ]; then
    DOCKER_SOCKET_GID="$($SUDO stat -c %g /var/run/docker.sock)"
  fi
}

forge_service_user() {
  if [ "$CONTROL_PLANE_USER" = "forgecloud" ]; then
    printf '    user: "%s:%s"' "$CP_UID" "$CP_GID"
    # The socket's group only while the socket is mounted; the mail socket's group, so a non-root
    # forge-cloud can create the socket and give it that group.
    if [ -n "$DOCKER_SOCKET_GID" ] || [ -n "$MAIL_CALLBACK_GID" ]; then printf '\n    group_add:'; fi
    if [ -n "$DOCKER_SOCKET_GID" ]; then printf '\n      - "%s"' "$DOCKER_SOCKET_GID"; fi
    if [ -n "$MAIL_CALLBACK_GID" ]; then printf '\n      - "%s"' "$MAIL_CALLBACK_GID"; fi
  fi
}

resolve_control_plane_docker_socket() {
  # An explicit FORGE_CONTROL_PLANE_DOCKER_SOCKET wins; otherwise the recorded layout is kept.
  requested="$(recorded_choice "${FORGE_CONTROL_PLANE_DOCKER_SOCKET:-}" "$DOCKER_SOCKET_MODE_PATH" mounted)"
  case "$requested" in
    mounted) DOCKER_SOCKET_MODE=mounted ;;
    removed)
      # Each prerequisite closes a root path the socket removal would otherwise leave open (spec §4.2):
      # a writable .env or compose file, uid 0, a Caddyfile forge-cloud writes, privileged BuildKit.
      is_image_mode || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires image mode; source installs keep the docker group."
      [ "$ENV_FILE_MODE" = "read_only" ] || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires FORGE_ENV_FILE_MODE=read_only."
      [ "$CONTROL_PLANE_USER" = "forgecloud" ] || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires FORGE_CONTROL_PLANE_USER=forgecloud."
      [ "$INGRESS_LAYOUT" = "isolated" ] || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires FORGE_INGRESS_LAYOUT=isolated."
      [ "$BUILDKIT_MODE" = "rootless_socket" ] || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires FORGE_BUILDKIT_MODE=rootless_socket."
      DOCKER_SOCKET_MODE=removed
      ;;
    *) fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET must be mounted or removed." ;;
  esac
}

require_socket_removal_prerequisites() {
  [ "$DOCKER_SOCKET_MODE" = "removed" ] || return 0
  env_file="$APP_DIR/.env"
  # Explicit helper selectors, so an older image started by a rollback reads them too.
  for selector in FORGE_HOST_OBSERVATION_SOURCE FORGE_HOST_INGRESS_SOURCE FORGE_HOST_SELF_UPDATE_SOURCE FORGE_HOST_MAINTENANCE_SOURCE; do
    [ "$(get_env_value "$env_file" "$selector")" = "helper" ] \
      || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires $selector=helper in $env_file (deliver it with the control_plane_host_isolation profile)."
  done
  for helper_family in $HOST_HELPER_FAMILIES; do
    $SUDO test -f "$DATA_DIR/host-helper/$helper_family/installed.json" \
      || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires the $helper_family host helper; rerun the installer without it first."
  done
  for key in FORGE_TRUSTED_LOCAL_RUNTIME_WORKSPACE_ID FORGE_TRUSTED_LOCAL_RUNTIME_SERVER_ID; do
    get_env_value "$env_file" "$key" | grep -Eq '^[A-Za-z0-9_-]{1,128}$' \
      || fail "FORGE_CONTROL_PLANE_DOCKER_SOCKET=removed requires $key; Forge's own workloads run on the trusted runtime."
  done
}

run_socket_removal_preflight() {
  [ "$DOCKER_SOCKET_MODE" = "removed" ] || return 0
  # Every run, plain reruns included: the host may have changed since the switch. Read-only and
  # offline, from the exact image being installed, before anything on the host is changed.
  say "Checking that nothing on this host still needs the control-plane Docker socket..."
  # deploy.db and its WAL files are 0600 to the forgecloud account, so root needs the read-only DAC bypass, nothing more.
  if ! preflight_output="$($SUDO docker run --rm --network none --read-only --cap-drop ALL --cap-add DAC_READ_SEARCH --security-opt no-new-privileges --user 0:0 \
    --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \
    --mount "type=bind,src=$DATA_DIR,dst=/source,readonly" \
    "$FORGE_IMAGE_DIGEST" node /app/dist/server/customer-state-digest-cli.js socket-removal-preflight \
    --database /source/deploy.db \
    --workspace "$(get_env_value "$APP_DIR/.env" FORGE_TRUSTED_LOCAL_RUNTIME_WORKSPACE_ID)" \
    --server "$(get_env_value "$APP_DIR/.env" FORGE_TRUSTED_LOCAL_RUNTIME_SERVER_ID)" \
    --buildkit-image "$(get_env_value "$APP_DIR/.env" FORGE_TRUSTED_LOCAL_RUNTIME_BUILDKIT_IMAGE)" 2>&1)"; then
    say "$preflight_output"
    fail "The Docker socket was not removed: the host still has workloads, a move or an evacuation that need it (FORGE_CONTROL_PLANE_SOCKET_REMOVAL_RUNBOOK.md)."
  fi
}

record_control_plane_docker_socket() {
  record_choice "$DOCKER_SOCKET_MODE" "$DOCKER_SOCKET_MODE_PATH" mounted
}

forge_install_mounts() {
  if [ "$DOCKER_SOCKET_MODE" = "removed" ]; then
    # Only the data directory is writable. compose.yml and the rest of the install directory are not
    # mounted; the Phase 0 trees the root worker writes are read-only (spec §12.1).
    printf '      - %s:%s\n' "$DATA_DIR" "$DATA_DIR"
    printf '      - %s:%s:ro\n' "$APP_DIR/phase0-evidence" "$APP_DIR/phase0-evidence"
    printf '      - %s:%s:ro' "$APP_DIR/phase0-input" "$APP_DIR/phase0-input"
  else
    printf '      - %s:%s' "$APP_DIR" "$APP_DIR"
  fi
}

forge_docker_socket_mount() {
  if [ "$DOCKER_SOCKET_MODE" = "mounted" ]; then
    printf '      - /var/run/docker.sock:/var/run/docker.sock'
  fi
}

forge_container_hardening() {
  if [ "$DOCKER_SOCKET_MODE" = "removed" ]; then
    printf '    cap_drop:\n      - ALL\n    security_opt:\n      - no-new-privileges:true\n    read_only: true\n    tmpfs:\n      - /tmp'
  fi
}

forge_docker_socket_environment() {
  if [ "$DOCKER_SOCKET_MODE" = "removed" ]; then
    # Caddy is applied only through the ingress helper (isolated layout), so there is no reload command.
    printf '      FORGE_CONTROL_PLANE_DOCKER_SOCKET: removed'
  else
    printf '      CADDY_RELOAD_CMD: docker exec deploy-caddy caddy reload --config /srv/deploy-data/Caddyfile --adapter caddyfile'
  fi
}

prepare_socket_free_mounts() {
  [ "$DOCKER_SOCKET_MODE" = "removed" ] || return 0
  # Created root-owned before Compose would create them, so a missing tree is never made writable.
  for tree in "$APP_DIR/phase0-evidence" "$APP_DIR/phase0-input"; do
    $SUDO test -d "$tree" || $SUDO install -d -m 0750 -o root -g "$CP_GID" "$tree"
  done
}

keep_previous_compose_file() {
  # Only when the layout changes, so a plain rerun never replaces the rollback copy with the current layout
  # (spec §6 Phase 9). Joining or leaving forge-control.slice is a layout change too.
  recorded_socket_mode="$(recorded_choice "" "$DOCKER_SOCKET_MODE_PATH" mounted)"
  [ -f "$APP_DIR/compose.yml" ] || return 0
  current_control_slice=false
  if $SUDO grep -qx '    cgroup_parent: forge-control.slice' "$APP_DIR/compose.yml"; then current_control_slice=true; fi
  if [ "$current_control_slice" != "${CONTROL_SLICE_ASSIGNED:-false}" ]; then CONTROL_SLICE_CHANGED=true; fi
  if [ "$recorded_socket_mode" != "$DOCKER_SOCKET_MODE" ] || [ "$CONTROL_SLICE_CHANGED" = "true" ]; then
    $SUDO cp -p "$APP_DIR/compose.yml" "$APP_DIR/compose.yml.previous"
  fi
}

resolve_control_slice() {
  # Compute spec §25.1 decision 5. forge-cloud, Caddy and BuildKit join forge-control.slice only when this run
  # confirms all of: image mode (only image installs write the slices); Docker's systemd cgroup driver, without
  # which cgroup_parent is not a systemd slice; and both forge.slice and forge-control.slice loaded from the
  # units forge-reserve-slices wrote. LoadState alone is not enough: systemd can load a slice name without a
  # unit file, with default settings and no MemoryLow, so FragmentPath and the file's first line are checked.
  # A failing probe means "not confirmed" and never stops the install. Nothing is recorded: a rerun with the
  # slice absent writes compose without cgroup_parent. The helper renders the units only after forge-cloud
  # starts, so a first install never assigns the slice; a later rerun does.
  CONTROL_SLICE_ASSIGNED=false
  if ! is_image_mode; then
    CONTROL_SLICE_DETAIL="source installs do not create the reserve slices"
    return 0
  fi
  slice_driver="$($SUDO docker info --format '{{.CgroupDriver}}' 2>/dev/null || true)"
  if [ "$slice_driver" != "systemd" ]; then
    CONTROL_SLICE_DETAIL="Docker reports the cgroup driver '${slice_driver:-unknown}', not systemd"
    return 0
  fi
  for slice_unit in forge.slice forge-control.slice; do
    slice_load="$($SUDO systemctl show -p LoadState --value "$slice_unit" 2>/dev/null || true)"
    slice_fragment="$($SUDO systemctl show -p FragmentPath --value "$slice_unit" 2>/dev/null || true)"
    slice_header="$($SUDO head -n 1 "$CONTROL_SLICE_UNIT_DIR/$slice_unit" 2>/dev/null || true)"
    if [ "$slice_load" != "loaded" ] || [ "$slice_fragment" != "$CONTROL_SLICE_UNIT_DIR/$slice_unit" ] \
      || [ "$slice_header" != "# Written by forge-reserve-slices from the measured capacity. Do not edit." ]; then
      CONTROL_SLICE_DETAIL="$slice_unit is not loaded from the unit forge-reserve-slices writes"
      return 0
    fi
  done
  CONTROL_SLICE_ASSIGNED=true
  CONTROL_SLICE_DETAIL="forge.slice and forge-control.slice are loaded and Docker uses the systemd cgroup driver"
}

control_slice_cgroup_parent() {
  # Printed with a leading newline after a service's restart line, so compose is byte-identical without the slice.
  if [ "${CONTROL_SLICE_ASSIGNED:-false}" = "true" ]; then
    printf '\n    cgroup_parent: forge-control.slice'
  fi
}

report_control_slice() {
  say ""
  if [ "$CONTROL_SLICE_ASSIGNED" = "true" ]; then
    say "Reserve slice: forge-cloud, Caddy and BuildKit run in forge-control.slice."
    if [ "$CONTROL_SLICE_CHANGED" = "true" ]; then
      say "  This rerun moved them there and recreated those three containers (a control-plane restart). The previous compose is compose.yml.previous."
    fi
  else
    say "Reserve slice: forge-cloud, Caddy and BuildKit are not in forge-control.slice ($CONTROL_SLICE_DETAIL)."
    if [ "$CONTROL_SLICE_CHANGED" = "true" ]; then
      say "  This rerun removed cgroup_parent from compose and recreated those three containers in their default cgroup. The previous compose is compose.yml.previous."
    fi
    case "$CONTROL_SLICE_DETAIL" in
      "Docker reports the cgroup driver"*)
        # Platform Admin shows "Reserve slice unsupported"; a rerun cannot help until Docker uses systemd.
        say "  The slice needs Docker's systemd cgroup driver; a rerun does not change this."
        ;;
      *)
        if is_image_mode; then
          say "  To apply it, wait until Platform Admin maintenance no longer shows \"Reserve slice missing\", then rerun this installer."
          say "  The rerun recreates forge-cloud, Caddy and BuildKit (a control-plane restart, with a short ingress gap and in-flight builds lost). Nothing applies it automatically."
        fi
        ;;
    esac
  fi
}

ownership_entry() {
  $SUDO stat -c '%u:%g %a' "$1"
}

refuse_foreign_bind_mounts() {
  # A customer container that binds a path under the install directory would have its files
  # re-owned, so the switch is refused. Only Forge's own three long-lived containers are expected.
  old_ifs="$IFS"
  for container in $($SUDO docker ps -aq); do
    name="$($SUDO docker inspect --format '{{.Name}}' "$container")"
    case "${name#/}" in
      forge-cloud|deploy-caddy|deploy-buildkit) continue ;;
    esac
    sources="$($SUDO docker inspect --format '{{range .Mounts}}{{if eq .Type "bind"}}{{.Source}}{{println}}{{end}}{{end}}' "$container")"
    IFS='
'
    for source in $sources; do
      case "$source" in
        "$APP_DIR"|"$APP_DIR"/*) IFS="$old_ifs"; fail "Container ${name#/} binds $source under $APP_DIR; the control-plane account was not changed." ;;
      esac
    done
    IFS="$old_ifs"
  done
}

control_plane_owned_paths() {
  # Everything forge-cloud writes, except the root helpers' trees, which get their own modes.
  # The data directory itself stays root-owned (see migrate_control_plane_ownership).
  $SUDO find "$DATA_DIR" -xdev -mindepth 1 \( -path "$DATA_DIR/host-helper" -o -path "$DATA_DIR/runtime-config-reconciler" -o -path "$DATA_DIR/host-observer" \) -prune -o -print
  for tree in "$APP_DIR/phase0-evidence" "$APP_DIR/phase0-input"; do
    $SUDO test -d "$tree" || continue
    $SUDO find "$tree" -xdev -print
  done
}

control_plane_request_files() {
  for path in "$DATA_DIR"/runtime-config-reconciler/request.json "$DATA_DIR"/runtime-config-reconciler/preflight-request.json "$DATA_DIR"/runtime-config-reconciler/hold-request.json "$DATA_DIR"/host-helper/*/request.json; do
    if $SUDO test -f "$path"; then printf '%s\n' "$path"; fi
  done
}

migrate_control_plane_ownership() {
  recorded=root
  if [ -f "$CONTROL_PLANE_USER_PATH" ]; then recorded="$($SUDO cat "$CONTROL_PLANE_USER_PATH")"; fi
  if [ "$recorded" != "$CONTROL_PLANE_USER" ]; then
    # forge-cloud is stopped so deploy.db and its -wal and -shm files change owner together.
    if $SUDO docker inspect forge-cloud >/dev/null 2>&1; then
      $SUDO docker stop forge-cloud >/dev/null
    fi
    if [ "$CONTROL_PLANE_USER" = "forgecloud" ]; then
      refuse_foreign_bind_mounts
      if control_plane_owned_paths | grep -q '[[:cntrl:]]'; then
        fail "A path under $APP_DIR contains a control character; the control-plane account was not changed."
      fi
      $SUDO install -d -m 0700 -o root -g root "$(dirname "$CONTROL_PLANE_OWNERSHIP_MANIFEST")"
      if ! $SUDO test -f "$CONTROL_PLANE_OWNERSHIP_MANIFEST"; then
        # The exact previous owner and mode of every path, so the switch back restores them.
        manifest_tmp="$(mktemp)"
        { printf '%s\n' "$DATA_DIR"; control_plane_owned_paths; control_plane_request_files; } | while IFS= read -r path; do
          printf '%s %s\n' "$(ownership_entry "$path")" "$path"
        done > "$manifest_tmp"
        $SUDO install -m 0600 -o root -g root "$manifest_tmp" "$CONTROL_PLANE_OWNERSHIP_MANIFEST"
        rm -f "$manifest_tmp"
      fi
      control_plane_owned_paths | while IFS= read -r path; do
        $SUDO chown -h "$CP_UID:$CP_GID" "$path"
      done
      # Root keeps the data directory, shared and sticky: forge-cloud creates its own files there but
      # cannot rename or replace the root helpers' directories, whose paths root later bind-mounts.
      $SUDO chown "root:$CP_GID" "$DATA_DIR"
      $SUDO chmod 1770 "$DATA_DIR"
      # Pending requests belong to the requester, which is now the forgecloud account.
      control_plane_request_files | while IFS= read -r path; do
        $SUDO chown -h "$CP_UID:$CP_GID" "$path"
      done
    else
      $SUDO test -f "$CONTROL_PLANE_OWNERSHIP_MANIFEST" || fail "No ownership manifest to restore; the control-plane account was not changed."
      $SUDO cat "$CONTROL_PLANE_OWNERSHIP_MANIFEST" | while IFS= read -r entry; do
        owner="${entry%% *}"
        rest="${entry#* }"
        mode="${rest%% *}"
        path="${rest#* }"
        if $SUDO test -L "$path"; then
          $SUDO chown -h "$owner" "$path"
        elif $SUDO test -e "$path"; then
          $SUDO chown "$owner" "$path"
          $SUDO chmod "$mode" "$path"
        fi
      done
      $SUDO mv "$CONTROL_PLANE_OWNERSHIP_MANIFEST" "$CONTROL_PLANE_OWNERSHIP_MANIFEST.restored-$(date -u +%Y%m%dT%H%M%SZ)"
    fi
  fi
  # .env stays root-owned; a non-root control plane reads it through its group.
  $SUDO chown "root:$CP_GID" "$APP_DIR/.env"
  $SUDO chmod "$CP_SHARED_FILE_MODE" "$APP_DIR/.env"
  for output in host-status.json result.json preflight-result.json hold-result.json hold-state.json; do
    if $SUDO test -f "$DATA_DIR/runtime-config-reconciler/$output"; then
      $SUDO chown "root:$CP_GID" "$DATA_DIR/runtime-config-reconciler/$output"
      $SUDO chmod "$CP_SHARED_FILE_MODE" "$DATA_DIR/runtime-config-reconciler/$output"
    fi
  done
  if [ "$CONTROL_PLANE_USER" = "forgecloud" ] || $SUDO test -f "$CONTROL_PLANE_USER_PATH"; then
    user_tmp="$(mktemp)"
    printf '%s\n' "$CONTROL_PLANE_USER" > "$user_tmp"
    $SUDO install -m 0644 -o root -g root "$user_tmp" "$CONTROL_PLANE_USER_PATH"
    rm -f "$user_tmp"
  fi
}

resolve_buildkit_mode() {
  requested="${FORGE_BUILDKIT_MODE:-}"
  if [ -z "$requested" ] && [ -f "$BUILDKIT_MODE_PATH" ]; then
    requested="$($SUDO cat "$BUILDKIT_MODE_PATH")"
  fi
  case "${requested:-privileged_tcp}" in
    privileged_tcp) BUILDKIT_MODE=privileged_tcp ;;
    rootless_socket)
      is_image_mode || fail "FORGE_BUILDKIT_MODE=rootless_socket requires image mode."
      BUILDKIT_MODE=rootless_socket
      BUILDKIT_IMAGE="${FORGE_BUILDKIT_IMAGE:-}"
      if [ -z "$BUILDKIT_IMAGE" ] && [ -f "$BUILDKIT_IMAGE_PATH" ]; then
        BUILDKIT_IMAGE="$($SUDO cat "$BUILDKIT_IMAGE_PATH")"
      fi
      # Only an exact digest the owner reviewed; a tag could change under the host.
      printf '%s' "$BUILDKIT_IMAGE" | grep -Eq '^[a-z0-9][a-z0-9./-]*@sha256:[a-f0-9]{64}$' \
        || fail "FORGE_BUILDKIT_MODE=rootless_socket requires FORGE_BUILDKIT_IMAGE pinned as <repository>@sha256:<digest>."
      ;;
    *) fail "FORGE_BUILDKIT_MODE must be privileged_tcp or rootless_socket." ;;
  esac
}

record_buildkit_mode() {
  if [ "$BUILDKIT_MODE" = "rootless_socket" ]; then
    $SUDO install -d -m 0755 -o root -g root "$(dirname "$BUILDKIT_SOCKET_DIR")"
    $SUDO install -d -m 0750 -o "$BUILDKIT_ROOTLESS_UID" -g "$CP_GID" "$BUILDKIT_SOCKET_DIR"
  fi
  if [ "$BUILDKIT_MODE" = "rootless_socket" ] || $SUDO test -f "$BUILDKIT_MODE_PATH"; then
    $SUDO install -d -m 0700 -o root -g root "$(dirname "$BUILDKIT_MODE_PATH")"
    mode_tmp="$(mktemp)"
    printf '%s\n' "$BUILDKIT_MODE" > "$mode_tmp"
    $SUDO install -m 0644 -o root -g root "$mode_tmp" "$BUILDKIT_MODE_PATH"
    if [ "$BUILDKIT_MODE" = "rootless_socket" ]; then
      printf '%s\n' "$BUILDKIT_IMAGE" > "$mode_tmp"
      $SUDO install -m 0644 -o root -g root "$mode_tmp" "$BUILDKIT_IMAGE_PATH"
    fi
    rm -f "$mode_tmp"
  fi
}

buildkit_address() {
  if [ "$BUILDKIT_MODE" = "rootless_socket" ]; then
    printf 'unix:///run/forge-buildkit/buildkitd.sock'
  else
    printf 'tcp://127.0.0.1:1234'
  fi
}

forge_buildkit_mount() {
  if [ "$BUILDKIT_MODE" = "rootless_socket" ]; then
    printf '      - %s:/run/forge-buildkit' "$BUILDKIT_SOCKET_DIR"
  fi
}

buildkit_compose_service() {
  if [ "$BUILDKIT_MODE" = "rootless_socket" ]; then
    # No --privileged and no TCP port. Builds run in a user namespace, so an insecure entitlement
    # cannot reach host root. A non-root forge-cloud reaches the socket through its group.
    cat <<BUILDKITEOF
  buildkit:
    image: $BUILDKIT_IMAGE
    container_name: deploy-buildkit
    user: "$BUILDKIT_ROOTLESS_UID:$BUILDKIT_ROOTLESS_UID"
    security_opt:
      - seccomp=unconfined
      - apparmor=unconfined
      - systempaths=unconfined
BUILDKITEOF
    if [ "$CP_GID" != "0" ]; then
      cat <<BUILDKITEOF
    group_add:
      - "$CP_GID"
    command: ["--addr", "unix:///run/buildkit/buildkitd.sock", "--group", "$CP_GID"]
BUILDKITEOF
    else
      cat <<BUILDKITEOF
    command: ["--addr", "unix:///run/buildkit/buildkitd.sock"]
BUILDKITEOF
    fi
    cat <<BUILDKITEOF
    volumes:
      - $BUILDKIT_SOCKET_DIR:/run/buildkit
      - buildkit_state:/home/user/.local/share/buildkit
    restart: unless-stopped$(control_slice_cgroup_parent)
BUILDKITEOF
    return
  fi
  cat <<BUILDKITEOF
  buildkit:
    image: moby/buildkit:latest
    container_name: deploy-buildkit
    privileged: true
    command: ["--addr", "tcp://0.0.0.0:1234"]
    ports:
      - "127.0.0.1:1234:1234"
    restart: unless-stopped$(control_slice_cgroup_parent)
BUILDKITEOF
}

recorded_choice() {
  # $1 explicit value, $2 recorded file, $3 default.
  if [ -n "$1" ]; then printf '%s' "$1"; return; fi
  if [ -f "$2" ]; then $SUDO cat "$2"; return; fi
  printf '%s' "$3"
}

record_choice() {
  # $1 value, $2 file, $3 default: records a non-default value, or any value once one was recorded.
  if [ "$1" != "$3" ] || $SUDO test -f "$2"; then
    $SUDO install -d -m 0700 -o root -g root "$(dirname "$2")"
    choice_tmp="$(mktemp)"
    printf '%s\n' "$1" > "$choice_tmp"
    $SUDO install -m 0644 -o root -g root "$choice_tmp" "$2"
    rm -f "$choice_tmp"
  fi
}

resolve_mail_and_port_access() {
  case "$(recorded_choice "${FORGE_MAIL_CALLBACK_TRANSPORT:-}" "$MAIL_CALLBACK_TRANSPORT_PATH" tcp_loopback)" in
    tcp_loopback) MAIL_CALLBACK_TRANSPORT=tcp_loopback ;;
    unix_socket)
      is_image_mode || fail "FORGE_MAIL_CALLBACK_TRANSPORT=unix_socket requires image mode."
      MAIL_CALLBACK_TRANSPORT=unix_socket
      ;;
    *) fail "FORGE_MAIL_CALLBACK_TRANSPORT must be tcp_loopback or unix_socket." ;;
  esac
  case "$(recorded_choice "${FORGE_CONTROL_PLANE_PORT_ACCESS:-}" "$PORT_ACCESS_PATH" open)" in
    open) PORT_ACCESS=open ;;
    caddy_only)
      is_image_mode || fail "FORGE_CONTROL_PLANE_PORT_ACCESS=caddy_only requires image mode."
      PORT_ACCESS=caddy_only
      ;;
    *) fail "FORGE_CONTROL_PLANE_PORT_ACCESS must be open or caddy_only." ;;
  esac
}

require_port_access_prerequisites() {
  [ "$PORT_ACCESS" = "caddy_only" ] || return 0
  # Without a Caddy-served https address the operator could not reach the dashboard at all.
  case "$(get_env_value "$APP_DIR/.env" PUBLIC_URL)" in
    https://*) ;;
    *) fail "FORGE_CONTROL_PLANE_PORT_ACCESS=caddy_only requires PUBLIC_URL to be the https address Caddy serves." ;;
  esac
  # The mail scripts run as their own accounts, which the firewall refuses; they must use the socket.
  if [ "$(get_env_value "$APP_DIR/.env" FORGE_EMAIL_ENABLED)" = "true" ] || [ "$(get_env_value "$APP_DIR/.env" FORGE_EMAIL_INBOUND_ENABLED)" = "true" ]; then
    [ "$MAIL_CALLBACK_TRANSPORT" = "unix_socket" ] || fail "FORGE_CONTROL_PLANE_PORT_ACCESS=caddy_only with email enabled requires FORGE_MAIL_CALLBACK_TRANSPORT=unix_socket."
  fi
  command -v iptables >/dev/null 2>&1 || fail "FORGE_CONTROL_PLANE_PORT_ACCESS=caddy_only requires iptables."
}

prepare_mail_callback_socket() {
  [ "$MAIL_CALLBACK_TRANSPORT" = "unix_socket" ] || return 0
  if ! getent group "$MAIL_CALLBACK_GROUP" >/dev/null 2>&1; then
    $SUDO groupadd --system "$MAIL_CALLBACK_GROUP"
  fi
  MAIL_CALLBACK_GID="$(getent group "$MAIL_CALLBACK_GROUP" | cut -d: -f3)"
  $SUDO install -d -m 0755 -o root -g root "$(dirname "$MAIL_CALLBACK_DIR")"
  # forge-cloud creates the socket here; the mail accounts in the group connect to it.
  if [ "$CP_UID" = "0" ]; then
    $SUDO install -d -m 0750 -o root -g "$MAIL_CALLBACK_GID" "$MAIL_CALLBACK_DIR"
  else
    $SUDO install -d -m 0770 -o root -g "$MAIL_CALLBACK_GID" "$MAIL_CALLBACK_DIR"
  fi
}

forge_network_environment() {
  if [ "$PORT_ACCESS" = "caddy_only" ]; then
    # Overrides .env: forge-cloud listens on loopback only, where Caddy reaches it.
    printf '      HOST: 127.0.0.1\n'
  fi
  if [ "$MAIL_CALLBACK_TRANSPORT" = "unix_socket" ]; then
    printf '      FORGE_MAIL_CALLBACK_TRANSPORT: unix_socket\n      FORGE_MAIL_CALLBACK_SOCKET: /run/forge-mail-callback/forge.sock\n      FORGE_MAIL_CALLBACK_GID: "%s"\n' "$MAIL_CALLBACK_GID"
  fi
}

forge_mail_callback_mount() {
  if [ "$MAIL_CALLBACK_TRANSPORT" = "unix_socket" ]; then
    printf '      - %s:/run/forge-mail-callback' "$MAIL_CALLBACK_DIR"
  fi
}

write_control_plane_firewall() {
  firewall_script="/usr/local/libexec/forge-control-plane-firewall"
  firewall_tmp="$(mktemp)"
  cat > "$firewall_tmp" <<FIREWALLEOF
#!/usr/bin/env sh
# Admits only root (Caddy, the root helpers) and the forge-cloud account to forge-cloud's port on
# loopback, and nothing from other interfaces. Its own chain; remove deletes every rule it added.
set -eu
chain=FORGE-CONTROL-PLANE
port=$PORT
control_plane_uid=$CP_UID
apply_family() {
  ipt="\$1"
  "\$ipt" -N "\$chain" 2>/dev/null || "\$ipt" -F "\$chain"
  "\$ipt" -A "\$chain" -m owner --uid-owner 0 -j RETURN
  if [ "\$control_plane_uid" != "0" ]; then "\$ipt" -A "\$chain" -m owner --uid-owner "\$control_plane_uid" -j RETURN; fi
  "\$ipt" -A "\$chain" -p tcp -j REJECT --reject-with tcp-reset
  "\$ipt" -C OUTPUT -o lo -p tcp --dport "\$port" -j "\$chain" 2>/dev/null || "\$ipt" -I OUTPUT 1 -o lo -p tcp --dport "\$port" -j "\$chain"
  "\$ipt" -C INPUT ! -i lo -p tcp --dport "\$port" -j DROP 2>/dev/null || "\$ipt" -I INPUT 1 ! -i lo -p tcp --dport "\$port" -j DROP
}
remove_family() {
  ipt="\$1"
  while "\$ipt" -C OUTPUT -o lo -p tcp --dport "\$port" -j "\$chain" 2>/dev/null; do "\$ipt" -D OUTPUT -o lo -p tcp --dport "\$port" -j "\$chain"; done
  while "\$ipt" -C INPUT ! -i lo -p tcp --dport "\$port" -j DROP 2>/dev/null; do "\$ipt" -D INPUT ! -i lo -p tcp --dport "\$port" -j DROP; done
  "\$ipt" -F "\$chain" 2>/dev/null || true
  "\$ipt" -X "\$chain" 2>/dev/null || true
}
for ipt in iptables ip6tables; do
  command -v "\$ipt" >/dev/null 2>&1 || continue
  case "\${1:-}" in
    apply) apply_family "\$ipt" ;;
    remove) remove_family "\$ipt" ;;
    *) echo "usage: forge-control-plane-firewall apply|remove" >&2; exit 64 ;;
  esac
done
FIREWALLEOF
  $SUDO install -m 0755 -o root -g root "$firewall_tmp" "$firewall_script"
  rm -f "$firewall_tmp"
  $SUDO tee /etc/systemd/system/forge-control-plane-firewall.service >/dev/null <<FIREWALLEOF
[Unit]
Description=Forge Cloud control-plane port firewall
Documentation=https://github.com/adeyomilawal/forge
After=network-pre.target docker.service
Wants=network-pre.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$firewall_script apply
ExecStop=$firewall_script remove

[Install]
WantedBy=multi-user.target
FIREWALLEOF
}

apply_control_plane_port_access() {
  if [ "$PORT_ACCESS" = "caddy_only" ]; then
    write_control_plane_firewall
    $SUDO systemctl daemon-reload
    $SUDO systemctl enable forge-control-plane-firewall.service >/dev/null
    # restart reapplies the rules for the current port and account.
    $SUDO systemctl restart forge-control-plane-firewall.service
  elif [ -f /etc/systemd/system/forge-control-plane-firewall.service ]; then
    # Back to open: stopping removes every rule the unit added.
    $SUDO systemctl disable --now forge-control-plane-firewall.service >/dev/null 2>&1 || true
  fi
  record_choice "$PORT_ACCESS" "$PORT_ACCESS_PATH" open
  record_choice "$MAIL_CALLBACK_TRANSPORT" "$MAIL_CALLBACK_TRANSPORT_PATH" tcp_loopback
}

forge_env_file_mount() {
  if [ "$ENV_FILE_MODE" = "read_only" ]; then
    printf '      - %s:%s:ro' "$APP_DIR/.env" "$APP_DIR/.env"
  fi
}

prepare_ingress_layout() {
  live_caddyfile="$INGRESS_DIR/Caddyfile"
  if [ "$INGRESS_LAYOUT" = "isolated" ]; then
    $SUDO install -d -m 0755 -o root -g root "$INGRESS_DIR"
    if ! $SUDO test -s "$live_caddyfile"; then
      # First switch: the live routes are the ones Caddy serves today. The legacy forge-cloud is
      # stopped first, so no route it writes after the copy can miss the new live file. Caddy keeps
      # serving; compose up starts forge-cloud again in the isolated layout.
      if $SUDO docker inspect forge-cloud >/dev/null 2>&1; then
        $SUDO docker stop forge-cloud >/dev/null
      fi
      $SUDO install -m 0644 -o root -g root "$DATA_DIR/Caddyfile" "$live_caddyfile"
    fi
  elif $SUDO test -f "$INGRESS_DIR/layout" && [ "$($SUDO cat "$INGRESS_DIR/layout")" = "isolated" ]; then
    # Rollback to the legacy layout: Caddy will read $DATA_DIR/Caddyfile again, so it must carry
    # the routes the isolated layout was serving. The mirror is refreshed from the live file.
    data_owner="$($SUDO stat -c %u:%g "$DATA_DIR/Caddyfile" 2>/dev/null || echo forgecloud:forgecloud)"
    $SUDO install -m 0644 -o "${data_owner%%:*}" -g "${data_owner##*:}" "$live_caddyfile" "$DATA_DIR/Caddyfile"
  fi
  if [ "$INGRESS_LAYOUT" = "isolated" ] || $SUDO test -d "$INGRESS_DIR"; then
    layout_tmp="$(mktemp)"
    printf '%s\n' "$INGRESS_LAYOUT" > "$layout_tmp"
    $SUDO install -m 0644 -o root -g root "$layout_tmp" "$INGRESS_DIR/layout"
    rm -f "$layout_tmp"
  fi
}

# The Caddy image reference for the generated compose file (FORGE_COMPUTE_RUNTIME_INFRA_SPEC.md, domain and TLS correctness D).
# A fresh install gets the multi-arch index digest of caddy:2 (2.11.9-alpine). A deploy-caddy that already exists keeps the image
# reference it was created with, because a changed reference makes `docker compose up` recreate it and routes would stop serving; it
# adopts the pin the next time it is recreated. FORGE_CADDY_IMAGE is the operator's explicit choice to change it, and must be a
# digest reference. That recreates deploy-caddy, so it belongs in a window.
CADDY_IMAGE_PINNED="caddy:2@sha256:ce773ec7a742ce15ee6bf2bb5f65882b9e2a4487b10733e6f1484f86e6b5d8bc"
caddy_image() {
  if [ -n "${FORGE_CADDY_IMAGE:-}" ]; then
    printf '%s' "$FORGE_CADDY_IMAGE" | grep -Eq '^[a-z0-9][a-z0-9./:_-]*@sha256:[a-f0-9]{64}$' \
      || fail "FORGE_CADDY_IMAGE must be a digest reference such as caddy@sha256:<64 hex digits>."
    printf '%s' "$FORGE_CADDY_IMAGE"
    return
  fi
  running_image="$($SUDO docker inspect --format '{{.Config.Image}}' deploy-caddy 2>/dev/null || true)"
  if [ -n "$running_image" ]; then
    printf '%s' "$running_image"
    return
  fi
  printf '%s' "$CADDY_IMAGE_PINNED"
}

caddy_compose_service() {
  caddy_image_reference="$(caddy_image)"
  if [ "$INGRESS_LAYOUT" = "isolated" ]; then
    cat <<CADDYEOF
  caddy:
    image: $caddy_image_reference
    container_name: deploy-caddy
    network_mode: host
    command: ["caddy", "run", "--config", "/etc/forge-ingress/Caddyfile", "--adapter", "caddyfile"]
    volumes:
      - $INGRESS_DIR:/etc/forge-ingress:ro
      - $DATA_DIR:/srv/deploy-data:ro
      - caddy_data:/data
      - caddy_config:/config
    restart: unless-stopped$(control_slice_cgroup_parent)
CADDYEOF
    return
  fi
  cat <<CADDYEOF
  caddy:
    image: $caddy_image_reference
    container_name: deploy-caddy
    network_mode: host
    command: ["sh", "-c", "mkdir -p /srv/deploy-data && touch /srv/deploy-data/Caddyfile && caddy run --config /srv/deploy-data/Caddyfile --adapter caddyfile --watch"]
    volumes:
      - $DATA_DIR:/srv/deploy-data
      - caddy_data:/data
      - caddy_config:/config
    restart: unless-stopped$(control_slice_cgroup_parent)
CADDYEOF
}

write_bootstrap_caddyfile() {
  caddyfile="$DATA_DIR/Caddyfile"
  if [ -s "$caddyfile" ]; then
    return
  fi

  candidate="$(mktemp)"
  cat > "$candidate" <<'EOF'
{
	auto_https off
}

http://127.0.0.1 {
	respond 503
}
EOF
  $SUDO install -m 0644 -o forgecloud -g forgecloud "$candidate" "$caddyfile"
  rm -f "$candidate"
}

build_forge() {
  say "Installing Forge dependencies..."
  cd "$APP_DIR"
  npm ci --include=dev
  if [ -f "$APP_DIR/website/package.json" ]; then
    say "Installing Forge website dependencies..."
    npm --prefix website ci
  fi

  say "Building Forge..."
  if [ -f "$APP_DIR/website/package.json" ]; then
    npm run build:production
  else
    npm run build
  fi
  npm prune --omit=dev --package-lock=false
}

write_compose_file() {
  if is_image_mode; then
    cat > "$APP_DIR/compose.yml" <<EOF
services:
  forge:
    image: \${FORGE_IMAGE:-ghcr.io/adeyomilawal/forge:latest}
    container_name: forge-cloud
$(forge_service_user)
    network_mode: host
    shm_size: 2g
    restart: unless-stopped$(control_slice_cgroup_parent)
$(forge_container_hardening)
    env_file:
      - .env
    environment:
      NODE_ENV: production
      FORGE_INSTALL_MODE: image
      FORGE_INSTALL_DIR: $APP_DIR
      FORGE_ENV_PATH: $APP_DIR/.env
      DATA_DIR: $DATA_DIR
      CADDY_CONFIG_PATH: $DATA_DIR/Caddyfile
      CADDY_DATA_DIR: /srv/deploy-data
$(forge_docker_socket_environment)
      BUILDKIT_HOST: $(buildkit_address)
      FORGE_INGRESS_LAYOUT: $INGRESS_LAYOUT
      FORGE_ENV_FILE_MODE: $ENV_FILE_MODE
$(forge_network_environment)
      HOME: $DATA_DIR/runtime-home
      DOCKER_CONFIG: $DATA_DIR/docker-config
    volumes:
$(forge_install_mounts)
$(forge_env_file_mount)
$(forge_buildkit_mount)
$(forge_mail_callback_mount)
$(forge_docker_socket_mount)
    depends_on:
      - buildkit
      - caddy

$(buildkit_compose_service)

$(caddy_compose_service)

volumes:
  caddy_data:
  caddy_config:
  buildkit_state:
EOF
    return
  fi

  cat > "$APP_DIR/compose.yml" <<EOF
services:
  buildkit:
    image: moby/buildkit:latest
    container_name: deploy-buildkit
    privileged: true
    command: ["--addr", "tcp://0.0.0.0:1234"]
    ports:
      - "127.0.0.1:1234:1234"
    restart: unless-stopped

$(caddy_compose_service)

volumes:
  caddy_data:
  caddy_config:
EOF
}

ensure_service_user() {
  if ! id forgecloud >/dev/null 2>&1; then
    $SUDO useradd --system --create-home --shell /bin/bash forgecloud
  fi
  if [ "$DOCKER_SOCKET_MODE" = "removed" ]; then
    # The host account forgecloud is a login account; membership of the docker group would be host root.
    $SUDO gpasswd -d forgecloud docker >/dev/null 2>&1 || true
  else
    $SUDO usermod -aG docker forgecloud >/dev/null 2>&1 || true
  fi
  $SUDO install -d -m 700 -o forgecloud -g forgecloud "$DATA_DIR/runtime-home" "$DATA_DIR/docker-config"
  if [ ! -f "$DATA_DIR/docker-config/config.json" ]; then
    printf '{}\n' | $SUDO tee "$DATA_DIR/docker-config/config.json" >/dev/null
  fi
  $SUDO chown forgecloud:forgecloud "$DATA_DIR/docker-config/config.json"
  $SUDO chmod 600 "$DATA_DIR/docker-config/config.json"
  if ! is_image_mode; then
    $SUDO chown -R forgecloud:forgecloud "$INSTALL_DIR"
  fi
}

write_systemd_unit() {
  command -v systemctl >/dev/null 2>&1 || fail "systemd is required to run Forge."

  if is_image_mode; then
    docker_cmd="$(docker_bin)"
    $SUDO tee /etc/systemd/system/forge-cloud.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud Docker image stack
Documentation=https://github.com/adeyomilawal/forge
After=network-online.target docker.service
Wants=network-online.target docker.service

[Service]
Type=oneshot
WorkingDirectory=$APP_DIR
RemainAfterExit=yes
Environment=DOCKER_CONFIG=$DATA_DIR/docker-config
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
ExecStart=$docker_cmd compose -f $APP_DIR/compose.yml up -d buildkit caddy forge
ExecReload=$docker_cmd compose -f $APP_DIR/compose.yml up -d buildkit caddy forge
ExecStop=$docker_cmd compose -f $APP_DIR/compose.yml stop forge
TimeoutStartSec=0
TimeoutStopSec=60

[Install]
WantedBy=multi-user.target
EOF
    return
  fi

  $SUDO tee /etc/systemd/system/forge-cloud.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud control plane
Documentation=https://github.com/adeyomilawal/forge
After=network-online.target docker.service
Wants=network-online.target docker.service

[Service]
Type=simple
User=forgecloud
Group=forgecloud
SupplementaryGroups=docker
WorkingDirectory=$APP_DIR
Environment=NODE_ENV=production
Environment=FORGE_ENV_PATH=$APP_DIR/.env
Environment=HOME=$DATA_DIR/runtime-home
Environment=DOCKER_CONFIG=$DATA_DIR/docker-config
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
EnvironmentFile=-$APP_DIR/.env
ExecStart=/usr/bin/env node dist/server/index.js
Restart=always
RestartSec=3
KillSignal=SIGTERM
TimeoutStopSec=30
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$APP_DIR/.env $DATA_DIR /var/run/docker.sock /tmp
PrivateTmp=true
PrivateDevices=false

[Install]
WantedBy=multi-user.target
EOF
}

write_runtime_config_reconciler() {
  runtime_config_dir="/etc/forgecloud"
  runtime_config_file="$runtime_config_dir/runtime-config-reconciler.json"
  runtime_age_identity="$runtime_config_dir/runtime-config-reconciler.agekey"
  runtime_age_recipient="$runtime_config_dir/runtime-config-reconciler.agepub"
  runtime_state_dir="$DATA_DIR/runtime-config-reconciler"
  runtime_wrapper="/usr/local/libexec/forge-runtime-config-reconciler"
  runtime_setup="/usr/local/sbin/forge-runtime-configure-doppler"

  $SUDO install -d -m 0700 -o root -g root "$runtime_config_dir"
  $SUDO install -d -m "$CP_REQUEST_DIR_MODE" -o root -g "$CP_GID" "$runtime_state_dir"
  $SUDO install -d -m 0755 -o root -g root /usr/local/libexec /usr/local/sbin

  if [ ! -f "$runtime_age_identity" ]; then
    runtime_key_tmp_dir="$(mktemp -d)"
    runtime_identity_tmp="$runtime_key_tmp_dir/identity"
    runtime_recipient_tmp="$runtime_key_tmp_dir/recipient"
    age-keygen -o "$runtime_identity_tmp" >/dev/null 2>&1
    age-keygen -y "$runtime_identity_tmp" > "$runtime_recipient_tmp"
    $SUDO install -m 0400 -o root -g root "$runtime_identity_tmp" "$runtime_age_identity"
    $SUDO install -m 0444 -o root -g root "$runtime_recipient_tmp" "$runtime_age_recipient"
    rm -f "$runtime_identity_tmp" "$runtime_recipient_tmp"
    rmdir "$runtime_key_tmp_dir"
  fi

  if [ ! -f "$runtime_config_file" ]; then
    runtime_config_tmp="$(mktemp)"
    cat > "$runtime_config_tmp" <<'EOF'
{"schemaVersion":1,"dopplerToken":"","project":"forge","config":"prd"}
EOF
    $SUDO install -m 0600 -o root -g root "$runtime_config_tmp" "$runtime_config_file"
    rm -f "$runtime_config_tmp"
  fi

  if [ ! -f "$runtime_state_dir/host-status.json" ]; then
    runtime_status_tmp="$(mktemp)"
    runtime_installed_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    cat > "$runtime_status_tmp" <<EOF
{"schemaVersion":1,"helperVersion":2,"installedAt":"$runtime_installed_at","checkedAt":null,"configured":false,"sourceProject":"forge","sourceConfig":"prd","availableProfiles":[],"missingProfiles":["cloudflare_dns_oauth","database_recovery_r2","trusted_first_party_local_runtime"],"errorCode":"RUNTIME_RECONCILER_CONFIGURATION_REQUIRED","message":"Configure the root-owned forge/prd Doppler service token on this host."}
EOF
    $SUDO install -m "$CP_SHARED_FILE_MODE" -o root -g "$CP_GID" "$runtime_status_tmp" "$runtime_state_dir/host-status.json"
    rm -f "$runtime_status_tmp"
  fi

  runtime_wrapper_tmp="$(mktemp)"
  cat > "$runtime_wrapper_tmp" <<EOF
#!/usr/bin/env sh
set -eu

mode="\${1:-}"
case "\$mode" in
  preflight|preflight-request|reconcile|hold|hold-init) ;;
  *) echo '{"ok":false,"failureCode":"HOST_MODE_INVALID"}' >&2; exit 64 ;;
esac

env_file="$APP_DIR/.env"
image="\$(sed -n 's/^FORGE_IMAGE=//p' "\$env_file" | tail -n 1 | sed 's/^["'"'"']//;s/["'"'"']$//')"
printf '%s' "\$image" | grep -Eq '^ghcr\.io/adeyomilawal/forge:sha-[0-9a-f]{40}$' \
  || { echo '{"ok":false,"failureCode":"HOST_IMAGE_NOT_IMMUTABLE"}' >&2; exit 65; }

exec /usr/bin/docker run --rm \
  --name "forge-runtime-config-reconciler-\$mode" \
  --label cc.forgecloud.resource=forge-task \
  --network host \
  --read-only \
  --cap-drop ALL \
  --cap-add DAC_OVERRIDE \
  --cap-add CHOWN \
  --cap-add FOWNER \
  --security-opt no-new-privileges \
  --pids-limit 128 \
  --memory 512m \
  --cpus 1 \
  --user 0:0 \
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777 \
  --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \
  --mount type=bind,src=$APP_DIR,dst=/host/forgecloud \
  --mount type=bind,src=$runtime_config_file,dst=/run/secrets/runtime-config-reconciler.json,readonly \
  --mount type=bind,src=$runtime_age_identity,dst=/run/secrets/runtime-config-reconciler.agekey,readonly \
  --mount type=bind,src=$runtime_age_recipient,dst=/run/secrets/runtime-config-reconciler.agepub,readonly \
  --env FORGE_RUNTIME_RECONCILER_HOST_ROOT=/host/forgecloud \
  --env FORGE_CONTROL_PLANE_UID=$CP_UID \
  --env FORGE_CONTROL_PLANE_GID=$CP_GID \
  "\$image" \
  node /app/dist/server/runtime-configuration-host-reconciler.js "\$mode"
EOF
  $SUDO install -m 0755 -o root -g root "$runtime_wrapper_tmp" "$runtime_wrapper"
  rm -f "$runtime_wrapper_tmp"

  runtime_setup_tmp="$(mktemp)"
  cat > "$runtime_setup_tmp" <<'EOF'
#!/usr/bin/env sh
set -eu

[ "$(id -u)" -eq 0 ] || { echo "Run this command through sudo." >&2; exit 77; }
trap 'stty echo 2>/dev/null || true; unset token' EXIT HUP INT TERM
printf 'forge/prd least-privilege Doppler service token: ' >&2
stty -echo
IFS= read -r token
stty echo
printf '\n' >&2
printf '%s' "$token" | grep -Eq '^[A-Za-z0-9._-]{20,2048}$' \
  || { echo "The Doppler service token format is invalid." >&2; exit 64; }

umask 077
temporary="$(mktemp /etc/forgecloud/.runtime-config-reconciler.XXXXXX)"
printf '{"schemaVersion":1,"dopplerToken":"%s","project":"forge","config":"prd"}\n' "$token" > "$temporary"
unset token
install -m 0600 -o root -g root "$temporary" /etc/forgecloud/runtime-config-reconciler.json
rm -f "$temporary"
/usr/local/libexec/forge-runtime-config-reconciler preflight
EOF
  $SUDO install -m 0755 -o root -g root "$runtime_setup_tmp" "$runtime_setup"
  rm -f "$runtime_setup_tmp"

  $SUDO tee /etc/systemd/system/forge-runtime-config-reconciler.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud root-owned runtime configuration reconciler
Documentation=https://github.com/adeyomilawal/forge
After=network-online.target docker.service forge-cloud.service
Wants=network-online.target docker.service

[Service]
Type=oneshot
ExecStart=/usr/bin/flock --wait 150 /run/forge-runtime-config-reconciler.lock $runtime_wrapper reconcile
TimeoutStartSec=180
User=root
Group=root
UMask=0077
Nice=5
IOSchedulingClass=best-effort
IOSchedulingPriority=6
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=$APP_DIR /var/run/docker.sock /run

[Install]
WantedBy=multi-user.target
EOF

  # Request-bound Admin preflight and the emergency hold use their own request files and path units.
  # They share the reconciler lock and wait for it, so a preflight, a hold change and a reconciliation
  # never run at the same time and none is silently skipped.
  for runtime_unit in preflight hold; do
    if [ "$runtime_unit" = "preflight" ]; then
      runtime_unit_mode="preflight-request"
      runtime_unit_request="preflight-request.json"
      runtime_unit_description="request-bound runtime configuration preflight"
    else
      runtime_unit_mode="hold"
      runtime_unit_request="hold-request.json"
      runtime_unit_description="trusted-runtime emergency hold"
    fi
    $SUDO tee "/etc/systemd/system/forge-runtime-config-$runtime_unit.service" >/dev/null <<EOF
[Unit]
Description=Forge Cloud root-owned $runtime_unit_description
Documentation=https://github.com/adeyomilawal/forge
After=network-online.target docker.service forge-cloud.service
Wants=network-online.target docker.service

[Service]
Type=oneshot
ExecStart=/usr/bin/flock --wait 150 /run/forge-runtime-config-reconciler.lock $runtime_wrapper $runtime_unit_mode
TimeoutStartSec=180
User=root
Group=root
UMask=0077
Nice=5
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=$APP_DIR /var/run/docker.sock /run

[Install]
WantedBy=multi-user.target
EOF
    $SUDO tee "/etc/systemd/system/forge-runtime-config-$runtime_unit.path" >/dev/null <<EOF
[Unit]
Description=Watch for Forge $runtime_unit_description requests
After=forge-cloud.service

[Path]
PathChanged=$runtime_state_dir/$runtime_unit_request
Unit=forge-runtime-config-$runtime_unit.service

[Install]
WantedBy=multi-user.target
EOF
  done

  $SUDO tee /etc/systemd/system/forge-runtime-config-reconciler.path >/dev/null <<EOF
[Unit]
Description=Watch for approved Forge runtime configuration reconciliation requests
After=forge-cloud.service

[Path]
PathChanged=$runtime_state_dir/request.json
Unit=forge-runtime-config-reconciler.service

[Install]
WantedBy=multi-user.target
EOF
}

write_host_observer() {
  # Root-owned read-only host observer (FORGE_CONTROL_PLANE_HOST_ISOLATION_SPEC.md Phase 2).
  # A timer runs one fixed entrypoint from the pinned immutable image; it reports the Docker daemon
  # version and the deploy-caddy/deploy-buildkit states only, and never observes customer containers.
  # forge-cloud reads the status file when FORGE_HOST_OBSERVATION_SOURCE=helper.
  observer_dir="$DATA_DIR/host-observer"
  observer_wrapper="/usr/local/libexec/forge-host-observer"
  $SUDO install -d -m 0755 -o root -g root "$observer_dir" /usr/local/libexec

  observer_wrapper_tmp="$(mktemp)"
  cat > "$observer_wrapper_tmp" <<EOF
#!/usr/bin/env sh
set -eu

env_file="$APP_DIR/.env"
image="\$(sed -n 's/^FORGE_IMAGE=//p' "\$env_file" | tail -n 1 | sed 's/^["'"'"']//;s/["'"'"']$//')"
printf '%s' "\$image" | grep -Eq '^ghcr\.io/adeyomilawal/forge:sha-[0-9a-f]{40}$' \\
  || { echo '{"ok":false,"failureCode":"HOST_IMAGE_NOT_IMMUTABLE"}' >&2; exit 65; }

exec /usr/bin/docker run --rm \\
  --name forge-host-observer \\
  --label cc.forgecloud.resource=forge-task \\
  --network none \\
  --read-only \\
  --cap-drop ALL \\
  --security-opt no-new-privileges \\
  --pids-limit 64 \\
  --memory 256m \\
  --cpus 0.5 \\
  --user 0:0 \\
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777 \\
  --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \\
  --mount type=bind,src=$observer_dir,dst=/host-observer \\
  "\$image" \\
  node /app/dist/server/host-observer-helper.js /host-observer/status.json
EOF
  $SUDO install -m 0755 -o root -g root "$observer_wrapper_tmp" "$observer_wrapper"
  rm -f "$observer_wrapper_tmp"

  $SUDO tee /etc/systemd/system/forge-host-observer.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud root-owned read-only host observer
Documentation=https://github.com/adeyomilawal/forge
After=docker.service
Wants=docker.service

[Service]
Type=oneshot
ExecStart=$observer_wrapper
TimeoutStartSec=60
User=root
Group=root
UMask=0022
Nice=10
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=$observer_dir /var/run/docker.sock
EOF

  $SUDO tee /etc/systemd/system/forge-host-observer.timer >/dev/null <<EOF
[Unit]
Description=Refresh the Forge Cloud host observer status

[Timer]
OnBootSec=1min
OnUnitActiveSec=2min
AccuracySec=15s

[Install]
WantedBy=timers.target
EOF
}

enable_host_observer() {
  $SUDO systemctl daemon-reload
  $SUDO systemctl enable --now forge-host-observer.timer
}

write_host_helpers() {
  # Root-owned host helpers (FORGE_CONTROL_PLANE_HOST_ISOLATION_SPEC.md §5.2). forge-cloud writes one
  # typed request file per family; a path unit runs one fixed entrypoint from the pinned immutable
  # image. The wrapper, not the request, decides the container's network and mounts.
  helper_root="$DATA_DIR/host-helper"
  helper_wrapper="/usr/local/libexec/forge-host-helper"
  helper_installed_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  $SUDO install -d -m 0755 -o root -g root /usr/local/libexec
  $SUDO install -d -m "$CP_READ_DIR_MODE" -o root -g "$CP_GID" "$helper_root"
  $SUDO install -d -m 0700 -o root -g root /etc/forgecloud
  $SUDO install -d -m 0700 -o root -g root "$OPERATOR_KEYS_DIR"
  $SUDO install -d -m 0755 -o root -g root "$COUNTERSIGN_DIR"
  $SUDO install -d -m 0700 -o root -g root "$MIGRATION_TUNNEL_DIR"
  $SUDO install -d -m 0700 -o root -g root "$RESERVE_SLICE_DIR"
  # forge-cloud writes pending security-key enrolments here; the root enrol command reads them as hostile input.
  $SUDO install -d -m "$CP_REQUEST_DIR_MODE" -o root -g "$CP_GID" "$DATA_DIR/operator-keys"
  $SUDO install -d -m "$CP_REQUEST_DIR_MODE" -o root -g "$CP_GID" "$DATA_DIR/operator-keys/pending"
  for helper_family in $HOST_HELPER_FAMILIES; do
    $SUDO install -d -m "$CP_REQUEST_DIR_MODE" -o root -g "$CP_GID" "$helper_root/$helper_family"
    helper_installed_tmp="$(mktemp)"
    cat > "$helper_installed_tmp" <<EOF
{"schemaVersion":1,"helperVersion":1,"family":"$helper_family","installedAt":"$helper_installed_at"}
EOF
    $SUDO install -m 0644 -o root -g root "$helper_installed_tmp" "$helper_root/$helper_family/installed.json"
    rm -f "$helper_installed_tmp"
    # Each family's start timeout covers its longest action plus the lock wait (host-helper-protocol.ts).
    case "$helper_family" in
      ingress) helper_timeout=420 ;;
      self_update) helper_timeout=720 ;;
      qualification) helper_timeout=2160 ;;
      inventory) helper_timeout=360 ;;
      maintenance) helper_timeout=840 ;;
      countersign) helper_timeout=240 ;;
      migration_source) helper_timeout=540 ;;
      *) fail "Unknown host helper family $helper_family" ;;
    esac
    $SUDO install -d -m 0755 -o root -g root "/etc/systemd/system/forge-host-helper@$helper_family.service.d"
    $SUDO tee "/etc/systemd/system/forge-host-helper@$helper_family.service.d/timeout.conf" >/dev/null <<EOF
[Service]
TimeoutStartSec=$helper_timeout
EOF
  done

  helper_wrapper_tmp="$(mktemp)"
  cat > "$helper_wrapper_tmp" <<EOF
#!/usr/bin/env sh
set -eu

family="\${1:-}"
# Only the ingress family sees the root-owned ingress directory, and only in the isolated layout.
ingress_mount="type=tmpfs,dst=/host-ingress,tmpfs-size=1m"
# Only the countersign family sees the helper key, and it never sees the Docker socket.
socket_mount="type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock"
key_mount="type=tmpfs,dst=/host-countersign-key,tmpfs-size=1m"
# Only the migration_source family sees the evacuation tunnel directories.
tunnel_mount="type=tmpfs,dst=/host-migration-tunnels,tmpfs-size=1m"
# Only the maintenance family sees the reserve-slice request directory.
slice_mount="type=tmpfs,dst=/host-reserve-slices,tmpfs-size=64k"
case "\$family" in
  ingress)
    network=none
    extra_mount="type=bind,src=$DATA_DIR,dst=/host-data"
    extra_cap=FOWNER
    if [ "$INGRESS_LAYOUT" = "isolated" ]; then
      ingress_mount="type=bind,src=$INGRESS_DIR,dst=/host-ingress"
    fi
    ;;
  self_update)
    # Registry access for manifest checks and pulls; the install directory at its own path, because
    # the image updater and restored-copy qualification it starts mount host paths under it.
    network=bridge
    extra_mount="type=bind,src=$APP_DIR,dst=$APP_DIR"
    extra_cap=CHOWN
    ;;
  qualification)
    # The restored-copy qualification container it starts needs no network; inputs live under data/.
    network=none
    extra_mount="type=bind,src=$APP_DIR,dst=$APP_DIR"
    extra_cap=CHOWN
    ;;
  inventory)
    # Quick read-only probes: registry manifests, container and image state, Phase 0 status.
    network=bridge
    extra_mount="type=bind,src=$APP_DIR,dst=$APP_DIR,readonly"
    extra_cap=DAC_OVERRIDE
    ;;
  maintenance)
    # deploy.db read-only: the helper computes the protected image set itself. It writes only
    # slices.env in the root-only reserve-slice directory; forge-reserve-slices renders the units.
    network=none
    extra_mount="type=bind,src=$DATA_DIR,dst=/host-data,readonly"
    slice_mount="type=bind,src=$RESERVE_SLICE_DIR,dst=/host-reserve-slices"
    extra_cap=DAC_OVERRIDE
    ;;
  countersign)
    # Verifies operator security-key approvals and signs with a key forge-cloud never holds. No
    # network and no Docker socket. The key and a writable registry are mounted only while .env is
    # root-owned and read-only, because .env names the image that would hold the key.
    network=none
    socket_mount="type=tmpfs,dst=/var/run/forge-no-docker,tmpfs-size=4k"
    extra_cap=DAC_OVERRIDE
    if [ "\$(cat /etc/forgecloud/env-file-mode 2>/dev/null || true)" = "read_only" ] \\
      && printf '%s' "\$(stat -c '%u %a' "$APP_DIR/.env")" | grep -Eq '^0 6[04]0$'; then
      extra_mount="type=bind,src=$OPERATOR_KEYS_DIR,dst=/host-operator-keys"
      key_mount="type=bind,src=$COUNTERSIGN_DIR,dst=/host-countersign-key,readonly"
    else
      extra_mount="type=bind,src=$OPERATOR_KEYS_DIR,dst=/host-operator-keys,readonly"
    fi
    ;;
  migration_source)
    # The source end of an evacuation tunnel. deploy.db read-only (the helper resolves the forward
    # port itself), the socket to inspect the source container and the tunnel process, and the
    # root-only tunnel directories. No network: the tunnel process, not the helper, listens.
    network=none
    extra_mount="type=bind,src=$DATA_DIR,dst=/host-data,readonly"
    tunnel_mount="type=bind,src=$MIGRATION_TUNNEL_DIR,dst=/host-migration-tunnels"
    extra_cap=CHOWN
    ;;
  *) echo '{"ok":false,"failureCode":"HOST_HELPER_FAMILY_INVALID"}' >&2; exit 64 ;;
esac

env_file="$APP_DIR/.env"
image="\$(sed -n 's/^FORGE_IMAGE=//p' "\$env_file" | tail -n 1 | sed 's/^["'"'"']//;s/["'"'"']$//')"
printf '%s' "\$image" | grep -Eq '^ghcr\.io/adeyomilawal/forge:sha-[0-9a-f]{40}$' \\
  || { echo '{"ok":false,"failureCode":"HOST_IMAGE_NOT_IMMUTABLE"}' >&2; exit 65; }

exec /usr/bin/docker run --rm \\
  --name "forge-host-helper-\$family" \\
  --label cc.forgecloud.resource=forge-task \\
  --network "\$network" \\
  --read-only \\
  --cap-drop ALL \\
  --cap-add DAC_OVERRIDE \\
  --cap-add FOWNER \\
  --cap-add "\$extra_cap" \\
  --security-opt no-new-privileges \\
  --pids-limit 64 \\
  --memory 512m \\
  --cpus 1 \\
  --user 0:0 \\
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777 \\
  --mount "\$socket_mount" \\
  --mount "type=bind,src=$helper_root/\$family,dst=/request" \\
  --mount "\$extra_mount" \\
  --mount "\$ingress_mount" \\
  --mount "\$key_mount" \\
  --mount "\$tunnel_mount" \\
  --mount "\$slice_mount" \\
  --env "FORGE_HOST_HELPER_INSTALL_DIR=$APP_DIR" \\
  --env "FORGE_CONTROL_PLANE_PORT=$PORT" \\
  --env "FORGE_INGRESS_LAYOUT=$INGRESS_LAYOUT" \\
  --env "FORGE_HOST_HELPER_IMAGE=\$image" \\
  "\$image" \\
  node /app/dist/server/host-helper.js "\$family" /request
EOF
  $SUDO install -m 0755 -o root -g root "$helper_wrapper_tmp" "$helper_wrapper"
  rm -f "$helper_wrapper_tmp"

  $SUDO tee /etc/systemd/system/forge-host-helper@.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud root-owned %i host helper
Documentation=https://github.com/adeyomilawal/forge
After=docker.service
Wants=docker.service

[Service]
Type=oneshot
ExecStart=/usr/bin/flock --wait 150 /run/forge-host-helper-%i.lock $helper_wrapper %i
TimeoutStartSec=420
User=root
Group=root
UMask=0077
Nice=5
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=$DATA_DIR /var/run/docker.sock /run
EOF

  $SUDO tee /etc/systemd/system/forge-host-helper@.path >/dev/null <<EOF
[Unit]
Description=Watch for Forge Cloud %i host helper requests
After=forge-cloud.service

[Path]
PathChanged=$helper_root/%i/request.json
Unit=forge-host-helper@%i.service

[Install]
WantedBy=multi-user.target
EOF
  write_migration_tunnel_units
  write_reserve_slice_units
}

write_migration_tunnel_units() {
  # Evacuation tunnels (host isolation spec §12.3 decision 2). The migration_source helper writes a
  # tunnel directory and a desired mark; the reconcile unit starts or stops one templated unit per
  # mark. Each unit opens a firewall chain for its port that admits only the target server, runs the
  # source end unprivileged from the pinned image, and removes the chain when it stops. Expired
  # tunnels are stopped by the timer even if forge-cloud never closes them.
  tunnel_firewall="/usr/local/libexec/forge-migration-tunnel-firewall"
  tunnel_runner="/usr/local/libexec/forge-migration-tunnel-run"
  tunnel_reconcile="/usr/local/libexec/forge-migration-tunnel-reconcile"
  tunnel_tmp="$(mktemp)"
  cat > "$tunnel_tmp" <<TUNNELEOF
#!/usr/bin/env sh
# apply|remove <tunnel-id>. Reads only PORT, TARGET and EXPIRES, each matched exactly.
set -eu
id="\${2:-}"
printf '%s' "\$id" | grep -Eq '^mtun_[a-z0-9]{20}\$' || { echo "invalid tunnel id" >&2; exit 64; }
values="$MIGRATION_TUNNEL_DIR/\$id/firewall.env"
chain="FMT-\$(printf '%s' "\$id" | cut -c6-25)"
port="\$(sed -n 's/^PORT=\\(47[0][0-9][0-9]\\)\$/\\1/p' "\$values" 2>/dev/null | head -n 1)"
target="\$(sed -n 's/^TARGET=\\([0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\)\$/\\1/p' "\$values" 2>/dev/null | head -n 1)"
remove() {
  for ipt in iptables ip6tables; do
    command -v "\$ipt" >/dev/null 2>&1 || continue
    for rule_port in \$(seq 47000 47099); do
      while "\$ipt" -C INPUT -p tcp --dport "\$rule_port" -j "\$chain" 2>/dev/null; do "\$ipt" -D INPUT -p tcp --dport "\$rule_port" -j "\$chain"; done
    done
    "\$ipt" -F "\$chain" 2>/dev/null || true
    "\$ipt" -X "\$chain" 2>/dev/null || true
  done
}
case "\${1:-}" in
  apply)
    [ -n "\$port" ] && [ -n "\$target" ] || { echo "tunnel firewall values invalid" >&2; exit 65; }
    remove
    iptables -N "\$chain"
    iptables -A "\$chain" -s "\$target/32" -j ACCEPT
    iptables -A "\$chain" -j DROP
    iptables -I INPUT 1 -p tcp --dport "\$port" -j "\$chain"
    if command -v ip6tables >/dev/null 2>&1; then
      # IPv4 only: nothing reaches the tunnel port over IPv6.
      ip6tables -N "\$chain"
      ip6tables -A "\$chain" -j DROP
      ip6tables -I INPUT 1 -p tcp --dport "\$port" -j "\$chain"
    fi
    ;;
  remove) remove ;;
  *) echo "usage: forge-migration-tunnel-firewall apply|remove <tunnel-id>" >&2; exit 64 ;;
esac
TUNNELEOF
  $SUDO install -m 0700 -o root -g root "$tunnel_tmp" "$tunnel_firewall"
  cat > "$tunnel_tmp" <<TUNNELEOF
#!/usr/bin/env sh
# run <tunnel-id>: the source end, unprivileged, from the pinned image, with only its own directory.
set -eu
id="\${1:-}"
printf '%s' "\$id" | grep -Eq '^mtun_[a-z0-9]{20}\$' || { echo "invalid tunnel id" >&2; exit 64; }
name="forge-migration-tunnel-\$id"
image="\$(sed -n 's/^FORGE_IMAGE=//p' "$APP_DIR/.env" | tail -n 1 | sed 's/^["'"'"']//;s/["'"'"']\$//')"
printf '%s' "\$image" | grep -Eq '^ghcr\\.io/adeyomilawal/forge:sha-[0-9a-f]{40}\$' || { echo "FORGE_IMAGE is not immutable" >&2; exit 65; }
exec /usr/bin/docker run --rm \\
  --name "\$name" \\
  --label cc.forgecloud.resource=forge-task \\
  --label "cc.forgecloud.migration-tunnel=\$id" \\
  --network host \\
  --read-only \\
  --cap-drop ALL \\
  --security-opt no-new-privileges \\
  --user 65534:65534 \\
  --pids-limit 64 \\
  --memory 256m \\
  --cpus 1 \\
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=8m,mode=1777 \\
  --mount "type=bind,src=$MIGRATION_TUNNEL_DIR/\$id,dst=/tunnel,readonly" \\
  "\$image" \\
  node /app/dist/server/migration-tunnel-source-cli.js /tunnel
TUNNELEOF
  $SUDO install -m 0700 -o root -g root "$tunnel_tmp" "$tunnel_runner"
  cat > "$tunnel_tmp" <<TUNNELEOF
#!/usr/bin/env sh
# Converges forge-migration-tunnel@ units to the desired marks; stops expired and unmarked tunnels.
set -eu
now="\$(date +%s)"
for directory in "$MIGRATION_TUNNEL_DIR"/mtun_*; do
  [ -d "\$directory" ] || continue
  id="\$(basename "\$directory")"
  printf '%s' "\$id" | grep -Eq '^mtun_[a-z0-9]{20}\$' || continue
  expires="\$(sed -n 's/^EXPIRES=\\([0-9]\\{10\\}\\)\$/\\1/p' "\$directory/firewall.env" 2>/dev/null | head -n 1)"
  if [ -f "\$directory/desired" ] && [ -n "\$expires" ] && [ "\$expires" -gt "\$now" ]; then
    systemctl is-active --quiet "forge-migration-tunnel@\$id.service" || systemctl start --no-block "forge-migration-tunnel@\$id.service"
  else
    rm -f "\$directory/desired"
    systemctl stop "forge-migration-tunnel@\$id.service" 2>/dev/null || true
  fi
done
TUNNELEOF
  $SUDO install -m 0700 -o root -g root "$tunnel_tmp" "$tunnel_reconcile"
  # Cutover freeze deadline (owner decision 2026-10-27): unpauses an evacuation's paused writers at the deadline the
  # helper recorded from the approved plan, unless the helper disarmed it just before the route switch. Only the exact
  # recorded container, still paused and in the same run, is unpaused. It shares the helper's per-evacuation lock.
  pause_reconcile="/usr/local/libexec/forge-migration-pause-reconcile"
  cat > "$tunnel_tmp" <<TUNNELEOF
#!/usr/bin/env sh
set -eu
now="\$(date +%s)"
for record in "$MIGRATION_TUNNEL_DIR"/pauses/evac_*/*.env; do
  [ -f "\$record" ] || continue
  dir="\$(dirname "\$record")"
  service="\$(basename "\$record" .env)"
  printf '%s' "\$(basename "\$dir")" | grep -Eq '^evac_[A-Za-z0-9_-]{20}\$' || continue
  printf '%s' "\$service" | grep -Eq '^[A-Za-z0-9_-]{1,128}\$' || continue
  [ -e "\$dir/\$service.disarmed" ] && continue
  [ -e "\$dir/\$service.expired" ] && continue
  deadline="\$(sed -n 's/^DEADLINE=\\([0-9]\\{10\\}\\)\$/\\1/p' "\$record" | head -n 1)"
  [ -n "\$deadline" ] && [ "\$deadline" -le "\$now" ] || continue
  lock="\$dir/lock.d"
  if ! mkdir "\$lock" 2>/dev/null; then
    # A lock older than two minutes belongs to a killed holder; the helper uses the same rule.
    [ -n "\$(find "\$lock" -maxdepth 0 -mmin +2 2>/dev/null)" ] && rmdir "\$lock" 2>/dev/null || true
    continue
  fi
  if [ ! -e "\$dir/\$service.disarmed" ]; then
    id="\$(sed -n 's/^CONTAINER_ID=\\([0-9a-f]\\{64\\}\\)\$/\\1/p' "\$record" | head -n 1)"
    started="\$(sed -n 's/^STARTED_AT=\\([0-9TZ:.+-]\\{1,40\\}\\)\$/\\1/p' "\$record" | head -n 1)"
    done_ok=1
    if [ -n "\$id" ] && [ -n "\$started" ]; then
      state="\$(/usr/bin/docker container inspect --format '{{.Id}} {{.State.Paused}} {{.State.StartedAt}}' "\$id" 2>/dev/null || true)"
      if [ "\$state" = "\$id true \$started" ]; then
        # A failed unpause is retried on the next tick; it never stalls the other records or keeps the lock.
        /usr/bin/docker container unpause "\$id" >/dev/null 2>&1 || done_ok=0
      fi
    fi
    [ "\$done_ok" = 1 ] && date -u +%Y-%m-%dT%H:%M:%SZ > "\$dir/\$service.expired"
  fi
  rmdir "\$lock" 2>/dev/null || true
done
TUNNELEOF
  $SUDO install -m 0700 -o root -g root "$tunnel_tmp" "$pause_reconcile"
  rm -f "$tunnel_tmp"

  $SUDO tee /etc/systemd/system/forge-migration-pauses.service >/dev/null <<EOF
[Unit]
Description=Unpause Forge Cloud evacuation writers whose approved pause window ended
After=docker.service

[Service]
Type=oneshot
ExecStart=$pause_reconcile
EOF

  $SUDO tee /etc/systemd/system/forge-migration-pauses.timer >/dev/null <<EOF
[Unit]
Description=Enforce Forge Cloud evacuation pause deadlines

[Timer]
OnBootSec=15s
OnUnitActiveSec=15s
AccuracySec=1s
Unit=forge-migration-pauses.service

[Install]
WantedBy=timers.target
EOF

  $SUDO tee /etc/systemd/system/forge-migration-tunnel@.service >/dev/null <<EOF
[Unit]
Description=Forge Cloud evacuation tunnel %i (source end)
Documentation=https://github.com/adeyomilawal/forge
After=docker.service network-online.target
Wants=docker.service

[Service]
Type=simple
ExecStartPre=$tunnel_firewall apply %i
ExecStart=$tunnel_runner %i
# The container goes before the chain, so its port is never left open without the firewall.
ExecStopPost=-/usr/bin/docker rm -f forge-migration-tunnel-%i
ExecStopPost=$tunnel_firewall remove %i
Restart=no
# No tunnel outlives its grant; the process also exits at its own expiry.
RuntimeMaxSec=86400
TimeoutStopSec=30
EOF

  $SUDO tee /etc/systemd/system/forge-migration-tunnels.service >/dev/null <<EOF
[Unit]
Description=Reconcile Forge Cloud evacuation tunnels
After=docker.service

[Service]
Type=oneshot
ExecStart=$tunnel_reconcile
EOF

  $SUDO tee /etc/systemd/system/forge-migration-tunnels.path >/dev/null <<EOF
[Unit]
Description=Watch for Forge Cloud evacuation tunnel changes

[Path]
PathChanged=$MIGRATION_TUNNEL_DIR/reconcile
Unit=forge-migration-tunnels.service

[Install]
WantedBy=multi-user.target
EOF

  $SUDO tee /etc/systemd/system/forge-migration-tunnels.timer >/dev/null <<EOF
[Unit]
Description=Stop expired Forge Cloud evacuation tunnels

[Timer]
OnBootSec=1min
OnUnitActiveSec=5min
Unit=forge-migration-tunnels.service

[Install]
WantedBy=timers.target
EOF
}

write_reserve_slice_units() {
  # Control-plane reserve slices (compute spec section 25.1 decision 5). The maintenance helper measures
  # the host and writes four integers to slices.env; this root script checks each against fixed bounds
  # and renders forge.slice, forge-tenants.slice and forge-control.slice from the template below. A value
  # that is not digits within bounds is refused and nothing is written. forge-cloud, Caddy and BuildKit
  # join forge-control.slice only through compose, and only when an operator reruns the installer
  # (resolve_control_slice).
  #
  # Why forge.slice gets MemoryLow too: a dash in a slice name is the hierarchy, so both slices sit under
  # forge.slice, not under -.slice. On cgroup v2 a child's memory.low only protects up to its parent's
  # effective protection, and a top-level cgroup's effective protection is its own memory.low. Without
  # MemoryLow on forge.slice, forge-control.slice's MemoryLow would protect nothing. forge.slice gets the
  # same CONTROL_MEMORY_LOW, so the host-wide protected amount stays the reserve. forge-control.slice
  # claims all of it while it uses at least that much. With memory_recursiveprot, protection that
  # forge-control.slice leaves unused can pass to forge-tenants.slice by usage; that is bounded by the
  # reserve and by the tenants' MemoryMax, and never lowers forge-control.slice's share. CPUWeight=1000
  # stays on forge-control.slice only: it competes with its sibling forge-tenants.slice, which is the
  # threat. forge.slice keeps the default weight, so dockerd and the OS in system.slice are not demoted.
  #
  # This script never removes or stops a slice unit: compose may reference forge-control.slice, and a
  # unit removed under it would put those containers in an unconfigured slice or fail their start.
  reserve_slice_script="/usr/local/libexec/forge-reserve-slices"
  reserve_slice_unit_dir="/etc/systemd/system"
  reserve_slice_tmp="$(mktemp)"
  {
    printf '#!/usr/bin/env sh\nset -eu\ndir="%s"\nunit_dir="%s"\n' "$RESERVE_SLICE_DIR" "$reserve_slice_unit_dir"
    cat <<'SLICEEOF'
values="$dir/slices.env"
request="$(sed -n 's/^REQUEST_ID=\(hhr_[A-Za-z0-9_-]\{16\}\)$/\1/p' "$values" 2>/dev/null | head -n 1)"
[ -n "$request" ] || exit 0
value() { sed -n "s/^$1=\([1-9][0-9]\{0,14\}\)\$/\1/p" "$values" 2>/dev/null | head -n 1; }
within() { [ -n "$1" ] && [ "$1" -ge "$2" ] && [ "$1" -le "$3" ]; }
answer() {
  answer_tmp="$dir/.applied.$$"
  printf 'REQUEST_ID=%s\nSTATUS=%s\n' "$request" "$1" > "$answer_tmp"
  chmod 0600 "$answer_tmp"
  mv -f "$answer_tmp" "$dir/applied.env"
}
tenant_memory_max="$(value TENANT_MEMORY_MAX)"
tenant_cpu_quota="$(value TENANT_CPU_QUOTA_PERCENT)"
tenant_tasks_max="$(value TENANT_TASKS_MAX)"
control_memory_low="$(value CONTROL_MEMORY_LOW)"
if ! within "$tenant_memory_max" 268435456 70368744177664 \
  || ! within "$tenant_cpu_quota" 10 102400 \
  || ! within "$tenant_tasks_max" 64 4194304 \
  || ! within "$control_memory_low" 4294967296 70368744177664; then
  answer refused
  echo "forge-reserve-slices: values are missing or out of bounds; nothing was written." >&2
  exit 65
fi
render_parent() {
  printf '# Written by forge-reserve-slices from the measured capacity. Do not edit.\n[Unit]\nDescription=Forge Cloud slices (parent of the control-plane reserve and tenant workloads)\nDocumentation=https://github.com/adeyomilawal/forge\n\n[Slice]\nMemoryLow=%s\n' "$control_memory_low"
}
render_tenants() {
  printf '# Written by forge-reserve-slices from the measured capacity. Do not edit.\n[Unit]\nDescription=Forge Cloud tenant workloads (allocatable capacity only)\nDocumentation=https://github.com/adeyomilawal/forge\n\n[Slice]\nMemoryMax=%s\nCPUQuota=%s%%\nTasksMax=%s\n' "$tenant_memory_max" "$tenant_cpu_quota" "$tenant_tasks_max"
}
render_control() {
  printf '# Written by forge-reserve-slices from the measured capacity. Do not edit.\n[Unit]\nDescription=Forge Cloud control-plane reserve\nDocumentation=https://github.com/adeyomilawal/forge\n\n[Slice]\nCPUWeight=1000\nMemoryLow=%s\n' "$control_memory_low"
}
changed=0
write_unit() {
  unit_tmp="$dir/.unit.$$"
  "$2" > "$unit_tmp"
  if ! cmp -s "$unit_tmp" "$unit_dir/$1"; then
    install -m 0644 -o root -g root "$unit_tmp" "$unit_dir/$1"
    changed=1
  fi
  rm -f "$unit_tmp"
}
write_unit forge.slice render_parent
write_unit forge-tenants.slice render_tenants
write_unit forge-control.slice render_control
if [ "$changed" = 1 ] && ! systemctl daemon-reload; then answer failed; exit 1; fi
if ! systemctl start forge-tenants.slice forge-control.slice; then answer failed; exit 1; fi
answer applied
SLICEEOF
  } > "$reserve_slice_tmp"
  $SUDO install -m 0700 -o root -g root "$reserve_slice_tmp" "$reserve_slice_script"
  rm -f "$reserve_slice_tmp"

  $SUDO tee /etc/systemd/system/forge-reserve-slices.service >/dev/null <<EOF
[Unit]
Description=Render Forge Cloud reserve slices from the maintenance helper's measurement
After=docker.service

[Service]
Type=oneshot
ExecStart=$reserve_slice_script
EOF

  $SUDO tee /etc/systemd/system/forge-reserve-slices.path >/dev/null <<EOF
[Unit]
Description=Watch for Forge Cloud reserve-slice requests

[Path]
PathChanged=$RESERVE_SLICE_DIR/slices.env
Unit=forge-reserve-slices.service

[Install]
WantedBy=multi-user.target
EOF
}

write_operator_key_command() {
  # Root-only security-key registry command (host isolation spec §12.3 decision 3): init, enrol with
  # a typed fingerprint check, list and revoke. It is the only path that adds a key. No network; the
  # enrolments forge-cloud wrote are mounted read-only and treated as hostile input. It refuses to run
  # while .env is writable, because .env names the image that writes the registry and the key.
  command_path="/usr/local/sbin/forge-operator-keys"
  command_tmp="$(mktemp)"
  cat > "$command_tmp" <<EOF
#!/usr/bin/env sh
set -eu

[ "\$(id -u)" = "0" ] || { echo "Run forge-operator-keys as root." >&2; exit 1; }
[ "\$(cat /etc/forgecloud/env-file-mode 2>/dev/null || true)" = "read_only" ] \\
  && printf '%s' "\$(stat -c '%u %a' "$APP_DIR/.env")" | grep -Eq '^0 6[04]0$' \\
  || { echo "forge-operator-keys needs FORGE_ENV_FILE_MODE=read_only and a root-owned .env no one else can write." >&2; exit 1; }
env_file="$APP_DIR/.env"
image="\$(sed -n 's/^FORGE_IMAGE=//p' "\$env_file" | tail -n 1 | sed 's/^["'"'"']//;s/["'"'"']$//')"
printf '%s' "\$image" | grep -Eq '^ghcr\.io/adeyomilawal/forge:sha-[0-9a-f]{40}$' \\
  || { echo "FORGE_IMAGE is not an immutable Forge image." >&2; exit 1; }

exec /usr/bin/docker run --rm -i \\
  --name forge-operator-keys \\
  --label cc.forgecloud.resource=forge-task \\
  --network none \\
  --read-only \\
  --cap-drop ALL \\
  --cap-add DAC_OVERRIDE \\
  --cap-add FOWNER \\
  --security-opt no-new-privileges \\
  --pids-limit 64 \\
  --memory 256m \\
  --user 0:0 \\
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=8m,mode=1777 \\
  --mount type=bind,src=$OPERATOR_KEYS_DIR,dst=/host-operator-keys \\
  --mount type=bind,src=$COUNTERSIGN_DIR,dst=/host-countersign-key \\
  --mount type=bind,src=$DATA_DIR/operator-keys/pending,dst=/pending,readonly \\
  "\$image" \\
  node /app/dist/server/operator-key-host-cli.js "\$@"
EOF
  $SUDO install -m 0750 -o root -g root "$command_tmp" "$command_path"
  rm -f "$command_tmp"
}

enable_host_helpers() {
  $SUDO systemctl daemon-reload
  for helper_family in $HOST_HELPER_FAMILIES; do
    $SUDO systemctl enable --now "forge-host-helper@$helper_family.path"
  done
  $SUDO systemctl enable --now forge-migration-tunnels.path forge-migration-tunnels.timer forge-migration-pauses.timer
  $SUDO systemctl enable --now forge-reserve-slices.path
}

write_control_plane_recovery_helper() {
  # Root-owned exact-revision recovery for a control plane that cannot serve Platform Admin.
  # No listener, no shell input: one reviewed 40-character revision, typed twice.
  recovery_helper="/usr/local/sbin/forge-control-plane-recover"
  recovery_helper_tmp="$(mktemp)"
  cat > "$recovery_helper_tmp" <<EOF
#!/usr/bin/env sh
set -eu

[ "\$(id -u)" -eq 0 ] || { echo "HOST_RECOVERY_ROOT_REQUIRED: run through sudo on the control-plane host." >&2; exit 77; }
target="\${1:-}"
confirm="\${2:-}"
printf '%s' "\$target" | grep -Eq '^[0-9a-f]{40}\$' \
  || { echo "Usage: sudo forge-control-plane-recover <40-character commit> <same commit>" >&2; exit 64; }
[ "\$target" = "\$confirm" ] || { echo "HOST_RECOVERY_CONFIRMATION_MISMATCH" >&2; exit 64; }

repository="ghcr.io/adeyomilawal/forge"
image="\$repository:sha-\$target"
/usr/bin/docker image pull "\$image" >/dev/null
revision="\$(/usr/bin/docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "\$image")"
[ "\$revision" = "\$target" ] || { echo "HOST_RECOVERY_IMAGE_UNVERIFIED" >&2; exit 65; }

exec /usr/bin/docker run --rm \\
  --name forge-host-recovery \\
  --label cc.forgecloud.resource=forge-task \\
  --network none \\
  --read-only \\
  --cap-drop ALL \\
  --cap-add DAC_OVERRIDE \\
  --cap-add CHOWN \\
  --cap-add FOWNER \\
  --security-opt no-new-privileges \\
  --pids-limit 128 \\
  --memory 1g \\
  --cpus 1 \\
  --user 0:0 \\
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777 \\
  --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \\
  --mount type=bind,src=$APP_DIR,dst=$APP_DIR \\
  --workdir $APP_DIR \\
  "\$image" \\
  node /app/dist/server/control-plane-update-recovery-cli.js recover \\
    --install-dir $APP_DIR --repository "\$repository" --target "\$target" --confirm-target "\$confirm"
EOF
  $SUDO install -d -m 0755 -o root -g root /usr/local/sbin
  $SUDO install -m 0750 -o root -g root "$recovery_helper_tmp" "$recovery_helper"
  rm -f "$recovery_helper_tmp"
}

enable_runtime_config_reconciler() {
  $SUDO systemctl daemon-reload
  $SUDO systemctl enable --now forge-runtime-config-reconciler.path
  $SUDO systemctl enable --now forge-runtime-config-preflight.path forge-runtime-config-hold.path
  # A known released revision-0 hold state; an existing state is never overwritten.
  if ! $SUDO /usr/local/libexec/forge-runtime-config-reconciler hold-init >/dev/null; then
    say "Warning: the runtime emergency hold state could not be initialized. Trusted-runtime admission stays refused until it is."
  fi
  if $SUDO grep -Eq '"dopplerToken":"[A-Za-z0-9._-]{20,2048}"' /etc/forgecloud/runtime-config-reconciler.json; then
    if ! $SUDO /usr/local/libexec/forge-runtime-config-reconciler preflight; then
      say "Warning: the root-owned runtime configuration source did not pass preflight. Open Platform Admin after installation for the bounded failure code."
    fi
  fi
}

start_runtime_services() {
  if is_image_mode; then
    return
  fi
  cd "$APP_DIR"
  say "Starting BuildKit and Caddy..."
  $SUDO docker compose up -d buildkit caddy
}

start_forge() {
  if is_image_mode; then
    say "Starting Forge Docker stack..."
  else
    say "Starting Forge..."
  fi
  $SUDO systemctl daemon-reload
  $SUDO systemctl enable --now forge-cloud
  $SUDO systemctl restart forge-cloud
}

print_firewall_hint() {
  if command -v ufw >/dev/null 2>&1 && $SUDO ufw status 2>/dev/null | grep -qi "Status: active"; then
    say ""
    say "UFW is active. Make sure these ports are allowed:"
    say "  sudo ufw allow 80/tcp"
    say "  sudo ufw allow 443/tcp"
    say "Keep the internal Forge port $PORT/tcp closed; Caddy reaches it locally."
    if [ "$EMAIL_INBOUND_ENABLED" = "true" ]; then
      say "  sudo ufw allow 25/tcp"
    fi
  fi
}

main() {
  require_linux
  normalize_install_mode
  resolve_ingress_layout
  resolve_env_file_mode
  resolve_control_plane_user
  resolve_buildkit_mode
  resolve_control_plane_docker_socket
  resolve_mail_and_port_access
  install_base_packages
  install_docker
  require_compose

  if is_image_mode; then
    prepare_image_install
  else
    install_node
    install_railpack
    clone_or_update_repo
  fi

  write_env_file
  require_socket_removal_prerequisites
  run_socket_removal_preflight
  if ! is_image_mode; then
    build_forge
  fi
  resolve_control_slice
  ensure_service_user
  resolve_control_plane_ids
  require_port_access_prerequisites
  prepare_mail_callback_socket
  prepare_socket_free_mounts
  keep_previous_compose_file
  write_compose_file
  write_bootstrap_caddyfile
  prepare_ingress_layout
  record_env_file_mode
  migrate_control_plane_ownership
  record_buildkit_mode
  record_control_plane_docker_socket
  write_systemd_unit
  write_runtime_config_reconciler
  if is_image_mode; then
    write_control_plane_recovery_helper
    write_host_observer
    write_host_helpers
    write_operator_key_command
  fi
  start_runtime_services
  start_forge
  enable_runtime_config_reconciler
  if is_image_mode; then
    enable_host_observer
    enable_host_helpers
    apply_control_plane_port_access
  fi

  public_url="$(get_env_value "$APP_DIR/.env" PUBLIC_URL)"
  print_firewall_hint
  report_control_slice
  say ""
  say "Forge is installed."
  say "Open: $public_url"
  if [ "$operator_bootstrap_token_generated" = "true" ]; then
    say "First-run bootstrap token: $(get_env_value "$APP_DIR/.env" FORGE_OPERATOR_BOOTSTRAP_TOKEN)"
    say "Enter this token only on the Forge operator onboarding screen."
  else
    say "Existing operator bootstrap token retained without disclosure."
  fi
  say ""
  say "Manage it with:"
  say "  sudo journalctl -u forge-cloud -f"
  if is_image_mode; then
    say "  cd $APP_DIR && sudo docker compose logs -f forge caddy buildkit"
    say "  cd $APP_DIR && sudo docker compose -f $APP_DIR/compose.yml pull forge && sudo systemctl restart forge-cloud"
  else
    say "  cd $INSTALL_DIR && git status"
    say "  cd $APP_DIR && sudo docker compose logs -f caddy buildkit"
  fi
}

main "$@"
