#!/bin/bash
set -e

# System-wide environment for all processes (hooks, ansible, etc.)

# Generate SSH keys if needed
/config/ssh/generate-keys.sh /ssh-keys

# Set up SSH
mkdir -p /root/.ssh
cp /ssh-keys/id_ed25519 /root/.ssh/id_ed25519
cp /ssh-keys/id_ed25519.pub /root/.ssh/id_ed25519.pub
chmod 700 /root/.ssh
chmod 600 /root/.ssh/id_ed25519
# Accept all host keys automatically
echo "StrictHostKeyChecking no" > /root/.ssh/config
echo "UserKnownHostsFile /dev/null" >> /root/.ssh/config
chmod 600 /root/.ssh/config

# Routing — DEFAULT_GATEWAY comes from docker-compose environment
# default: 10.226.1.1 (fw-isp), direct-internet: 10.226.1.254 (fw-main)
GATEWAY="${DEFAULT_GATEWAY:-10.226.1.1}"
# Next hop into the segmented zones. On the default topology celilo-mgr is on the
# internal LAN and reaches them via fw-main's internal leg (10.226.1.254). When
# celilo-mgr lives on its OWN control-plane network (managementZone secure-mgmt),
# it reaches them via fw-main's leg on THAT network instead.
FW_MAIN="${FW_MAIN_HOP:-10.226.1.254}"
ip route del default 2>/dev/null || true
ip route add default via "$GATEWAY"
ip route add 10.226.10.0/24 via "$FW_MAIN"    # dmz via fw-main
ip route add 10.226.20.0/24 via "$FW_MAIN"    # app via fw-main
ip route add 10.226.30.0/24 via "$FW_MAIN"    # secure via fw-main
# Control plane. Only reachable when a secure-mgmt network exists — that is,
# when celilo-mgr lives there itself, or when a module declaring
# `zone: secure-mgmt` needs a system to land on (#436). Tolerated silently
# otherwise so the default topology is unchanged.
ip route add 10.226.120.0/24 via "$FW_MAIN" 2>/dev/null || true

# DNS — Technitium internal resolver (split-horizon) with public fallback.
# Technitium at 10.226.1.10 is authoritative for iamtheinternet.org internally,
# resolving www/auth to Caddy's DMZ IP (10.226.10.10) rather than the public WAN IP.
# Fall back to the simulated public resolver if Technitium is not yet up.
printf 'nameserver %s\nnameserver 203.0.113.1\n' "${INTERNAL_RESOLVER:-10.226.1.10}" > /etc/resolv.conf

# Fetch Pebble's runtime ACME root CA (Pebble generates a fresh root at each
# startup, unlike the static /config/pebble/pebble-ca.crt baked in at build
# time which only signs Pebble's own API endpoint). Without this, management
# can't verify certs that Caddy obtained from Pebble (iamtheinternet.org,
# isitup.org, etc.). Mirrors the equivalent block in fw-ext-routes.sh.
# NOTE: this fetch is *foreground* (no `&`) — used to be backgrounded,
# which caused a race where fast deploys (config-only modules like
# celilo-website) reached health_check before update-ca-certificates
# had refreshed /etc/ssl/certs/ca-certificates.crt with the current
# Pebble runtime root. bun's fetch() then failed with "unable to get
# local issuer certificate" against any HTTPS endpoint Pebble had
# signed. Confirmed bitten 2026-05-06: caddy tests passed (slow
# deploys outran the race), website-deploy-simple / website-deploy-
# cross-domain / registry-pipeline failed. Worst case here is ~2 min if
# Pebble is unreachable; in practice the loop exits in ~1s because
# Pebble (shared infra) is up before management (per-test) starts.
echo "Waiting for Pebble ACME root CA..."
for i in $(seq 1 60); do
  if curl -sk https://100.64.0.100:15000/roots/0 -o /usr/local/share/ca-certificates/pebble-acme-root.crt 2>/dev/null; then
    if [ -s /usr/local/share/ca-certificates/pebble-acme-root.crt ]; then
      update-ca-certificates 2>/dev/null
      echo "Pebble ACME root CA installed"
      break
    fi
  fi
  sleep 2
done

# Create celilo data directory (Linux default: /var/lib/celilo/)
mkdir -p /var/lib/celilo/modules

# If the monorepo is mounted at /celilo, use it for shell completions (dev mode).
# Otherwise use the globally installed CLI from npm.
if [ -d /celilo/apps/celilo ]; then
  CELILO_SRC="/celilo/apps/celilo/src/cli/index.ts"
  CELILO_CMD="bun run $CELILO_SRC"

  # Warn if node_modules are missing (developer forgot to bun install)
  if [ ! -d /celilo/apps/celilo/node_modules/@clack ]; then
    echo "WARNING: /celilo/apps/celilo/node_modules not found. Run 'cd apps/celilo && bun install' on the host."
  fi

  # Generate zsh completions from source
  mkdir -p /root/.zsh/completions
  bun run "$CELILO_SRC" completion zsh > /root/.zsh/completions/_celilo 2>/dev/null || true

  START_DIR="/celilo/apps/celilo"
else
  CELILO_CMD="celilo"
  START_DIR="/root"

  # Generate zsh completions from npm-installed CLI
  mkdir -p /root/.zsh/completions
  celilo completion zsh > /root/.zsh/completions/_celilo 2>/dev/null || true
fi

# Shell setup
cat > /root/.zshrc << ZSHRC
export PATH="/root/.bun/bin:/usr/local/bin:\$PATH"

# Simulated network overrides

# History
HISTFILE=/root/.zsh_history
HISTSIZE=10000
SAVEHIST=10000
setopt SHARE_HISTORY
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_SPACE

# Key bindings — emacs mode (ctrl-p/n for history, ctrl-a/e, etc.)
bindkey -e
bindkey '^P' up-history
bindkey '^N' down-history
bindkey '^R' history-incremental-search-backward

# Prompt
PROMPT='%F{cyan}celilo%f:%F{yellow}%~%f# '

# Commands — celilo shim in /usr/local/bin prefers source when /celilo is mounted
alias c='celilo'
alias ll='ls -la'

# Tab completion
fpath=(~/.zsh/completions \$fpath)
autoload -Uz compinit && compinit -u

cd $START_DIR
ZSHRC

# Bash fallback (for non-zsh shells)
cat > /root/.bashrc << BASHRC
export PATH="/root/.bun/bin:/usr/local/bin:\$PATH"
alias c='celilo'
cd $START_DIR
BASHRC

echo "Management machine ready"
sleep infinity
