#!/usr/bin/env bash
# Installs the Boujot isolation service on Linux (systemd). Run as root.
#
#   install.sh --owner <user> --binary <boujot-isolator> \
#              --boujot-package <dir of @boujot/happy-coder> \
#              --node-root <Node install dir with bin/node> \
#              --codex-dir <folder with codex and its helper programs> \
#              (--claude <the claude program> | --without-claude) \
#              [--security-test <probe script>] [--network-policy <reviewed JSON>]
#              [--no-start]
#
# Build the binary as an ordinary user. Drain chats, stop the daemon and both
# root services before installing. This installer refuses active or uncertain
# units; it never stops them. Existing configurations and unit files are kept.
# --network-policy changes only the main service's owner-reviewed network
# policy and adds its exact model gateway token name to the environment list.
#
# Every value is required; nothing is guessed. Program paths are resolved at
# each runtime launch, so upgrading Boujot, Node, Codex or Claude needs no
# reinstall. Codex runs commands through helper programs beside it
# (codex-code-mode-host), so its whole folder is mounted, never the program
# alone. For the standalone Codex, give the stable folder
# <home>/.codex/packages/standalone/current/bin.
# Claude's native install is one program file; give the stable link
# <home>/.local/bin/claude: each launch mounts the version it points to at
# /opt/boujot/claude/claude. A Claude installed with npm is a script that
# needs its package folder, so it is refused.
set -euo pipefail

die() { echo "install: $*" >&2; exit 1; }
[ "$(id -u)" = 0 ] || die "run as root"

OWNER='' BINARY='' PACKAGE='' NODE_ROOT='' CODEX_DIR='' CLAUDE='' WITHOUT_CLAUDE='' PROBE='' NETWORK_POLICY='' NO_START=''
INSTALLER_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
while [ $# -gt 0 ]; do
  case "$1" in
    --owner) OWNER="$2"; shift 2;;
    --binary) BINARY="$2"; shift 2;;
    --boujot-package) PACKAGE="$2"; shift 2;;
    --node-root) NODE_ROOT="$2"; shift 2;;
    --codex-dir) CODEX_DIR="$2"; shift 2;;
    --codex) die "--codex is replaced by --codex-dir <folder with codex and codex-code-mode-host>";;
    --claude) CLAUDE="$2"; shift 2;;
    --without-claude) WITHOUT_CLAUDE=yes; shift;;
    --security-test) PROBE="$2"; shift 2;;
    --network-policy) NETWORK_POLICY="$2"; shift 2;;
    --no-start) NO_START=yes; shift;;
    *) die "unknown argument: $1";;
  esac
done
for pair in OWNER:--owner BINARY:--binary PACKAGE:--boujot-package NODE_ROOT:--node-root CODEX_DIR:--codex-dir; do
  name="${pair%%:*}"
  [ -n "${!name}" ] || die "${pair#*:} is required"
done
id "$OWNER" >/dev/null 2>&1 || die "user $OWNER does not exist"
OWNER_HOME="$(getent passwd "$OWNER" | cut -d: -f6)"
[ -x "$BINARY" ] || die "binary $BINARY is not executable"
[ -f "$PACKAGE/dist/index.mjs" ] || die "$PACKAGE is not a Boujot package (no dist/index.mjs)"
[ -x "$NODE_ROOT/bin/node" ] || die "$NODE_ROOT has no bin/node"
[ -x "$CODEX_DIR/codex" ] || die "$CODEX_DIR has no executable codex"
[ -x "$CODEX_DIR/codex-code-mode-host" ] || die "$CODEX_DIR has no codex-code-mode-host: give the folder of a complete Codex install"
[ -z "$PROBE" ] || [ -f "$PROBE" ] || die "probe $PROBE does not exist"
[ -z "$NETWORK_POLICY" ] || [ -f "$NETWORK_POLICY" ] || die "network policy does not exist"
if [ -n "$CLAUDE" ] && [ -n "$WITHOUT_CLAUDE" ]; then die "give --claude or --without-claude, not both"; fi
[ -n "$CLAUDE" ] || [ -n "$WITHOUT_CLAUDE" ] || die "--claude <the claude program> or --without-claude is required"
if [ -n "$CLAUDE" ]; then
  # The service needs an absolute source, and the path goes into JSON as it is.
  case "$CLAUDE" in /*) ;; *) die "--claude needs an absolute path: $CLAUDE";; esac
  case "$CLAUDE" in *[\"\\]*|*[[:cntrl:]]*) die "--claude path holds a quote, a backslash or a control character: $CLAUDE";; esac
  CLAUDE_FILE="$(readlink -f "$CLAUDE")" || die "$CLAUDE does not resolve"
  [ -f "$CLAUDE_FILE" ] && [ -x "$CLAUDE_FILE" ] || die "$CLAUDE is not an executable file"
  [ "$(head -c 2 "$CLAUDE_FILE")" != '#!' ] || die "$CLAUDE is a script (an npm install); give Claude's native program"
fi
command -v systemd-run >/dev/null || die "systemd-run is missing"
SYSTEMD_VERSION="$(systemctl --version | awk 'NR==1{print $2}')"
[ "$SYSTEMD_VERSION" -ge 247 ] || die "systemd $SYSTEMD_VERSION is too old (need 247 or newer)"

# The socket belongs to the owner's primary group, which must contain the
# owner only: then only the owner's daemon can connect, with no group change
# (and no re-login) needed.
GROUP="$(id -gn "$OWNER")"
GID="$(id -g "$OWNER")"
OTHERS="$( { getent passwd | awk -F: -v gid="$GID" -v owner="$OWNER" '$4==gid && $1!=owner {print $1}'; \
            getent group "$GROUP" | cut -d: -f4 | tr ',' '\n' | grep -vx "$OWNER" | grep -v '^$'; } || true)"
[ -z "$OTHERS" ] || die "group $GROUP also contains: $OTHERS"

# A stopped root service cannot admit a new runtime between this check and
# installation. Retired registry records are not live units and are retained.
"$NODE_ROOT/bin/node" "$INSTALLER_DIR/preflight.mjs" "$(command -v systemctl)" || die "installation preflight refused"
STAGE="$(mktemp -d /tmp/boujot-isolator-install.XXXXXXXX)"
chmod 0700 "$STAGE"
trap 'rm -rf -- "$STAGE"' EXIT
SHARED="$OWNER_HOME/.boujot/runtime-shared"

write_config() { # <basename> <state name> <socket> <registry> <diagnostics> <run dir> <runtime|probe> <policy>
  "$NODE_ROOT/bin/node" "$INSTALLER_DIR/configure.mjs" \
    --output "$STAGE/$1" --existing "/etc/boujot-isolator/$1" \
    --state-name "$2" --socket "$3" --registry-dir "$4" --diagnostics-root "$5" \
    --run-dir "$6" --runtime-kind "$7" --owner-group "$GROUP" --shared "$SHARED" \
    --package "$PACKAGE" --node-root "$NODE_ROOT" --codex-dir "$CODEX_DIR" \
    --claude "$CLAUDE" --probe "$PROBE" --network-policy "$8" \
    --systemd-run "$(command -v systemd-run)" --systemctl "$(command -v systemctl)"
  "$BINARY" check-config "$STAGE/$1" || die "candidate binary refused staged configuration"
  # Existing mounts are preserved: validate the effective source, not just --boujot-package.
  "$NODE_ROOT/bin/node" "$INSTALLER_DIR/package-access.mjs" --config "$STAGE/$1" \
    || die "isolated workers cannot read the configured runtime package"
}

CREATED_UNITS=''
write_unit() { # <unit name> <config file> <description>
  if [ -e "/etc/systemd/system/$1" ]; then
    [ -f "/etc/systemd/system/$1" ] && [ ! -L "/etc/systemd/system/$1" ] || die "existing unit must be a regular file: $1"
    echo "Preserved installed unit $1."
    return
  fi
  cat > "/etc/systemd/system/$1" <<UNIT
[Unit]
Description=$3
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/libexec/boujot-isolator serve $2
Restart=on-failure
RestartSec=2
# Runtimes are separate transient units. Drain them before maintenance:
# restarting this service loses the protected runtimes' live network handles.
KillMode=process

[Install]
WantedBy=multi-user.target
UNIT
  CREATED_UNITS="$CREATED_UNITS $1"
}

write_config config.json boujot /run/boujot-isolator.sock \
  /var/lib/boujot-isolator /var/log/boujot-isolator /run/boujot-isolator \
  runtime "$NETWORK_POLICY"

UNITS=boujot-isolator.service
if [ -n "$PROBE" ]; then
  write_config sectest.json boujot-sectest /run/boujot-isolator-sectest.sock \
    /var/lib/boujot-isolator-sectest /var/log/boujot-isolator-sectest /run/boujot-isolator-sectest \
    probe ''
  UNITS="$UNITS boujot-isolator-sectest.service"
elif [ -e /etc/boujot-isolator/sectest.json ]; then
  # Both instances share the binary. Even an untouched, stopped test instance
  # must remain compatible with it.
  "$BINARY" check-config /etc/boujot-isolator/sectest.json || die "candidate binary refused installed test configuration"
fi

# All configurations and the stopped-unit precondition pass before installed
# files change. Recheck immediately before replacement, without stopping units.
"$NODE_ROOT/bin/node" "$INSTALLER_DIR/preflight.mjs" "$(command -v systemctl)" || die "installation preflight changed"
install -D -o root -g root -m 0755 "$BINARY" /usr/local/libexec/boujot-isolator
install -d -o root -g root -m 0755 /etc/boujot-isolator
install -o root -g root -m 0600 "$STAGE/config.json" /etc/boujot-isolator/config.json
install -d -o "$OWNER" -g "$GROUP" -m 0755 "$SHARED"
install -d -o root -g root -m 0755 /opt/boujot /opt/boujot/bin /opt/boujot/node /opt/boujot/happy-coder /opt/boujot/codex
if [ -n "$CLAUDE" ]; then
  install -d -o root -g root -m 0755 /opt/boujot/claude
  [ -e /opt/boujot/claude/claude ] || install -o root -g root -m 0755 /dev/null /opt/boujot/claude/claude
fi
write_unit boujot-isolator.service /etc/boujot-isolator/config.json "Boujot isolation service"
if [ -n "$PROBE" ]; then
  install -D -o root -g root -m 0755 "$PROBE" /usr/local/libexec/boujot-isolator-probe
  rm -f /opt/boujot/bin/boujot-isolator-probe
  install -o root -g root -m 0600 "$STAGE/sectest.json" /etc/boujot-isolator/sectest.json
  write_unit boujot-isolator-sectest.service /etc/boujot-isolator/sectest.json "Boujot isolation service (security test instance)"
fi

systemctl daemon-reload
for unit in $UNITS; do
  case " $CREATED_UNITS " in *" $unit "*) systemctl enable "$unit" >/dev/null;; esac
  [ -n "$NO_START" ] || systemctl start "$unit"
done
[ -z "$NO_START" ] || { echo "installed, left stopped: $UNITS"; exit 0; }
sleep 1
for unit in $UNITS; do
  systemctl is-active --quiet "$unit" || { journalctl -u "$unit" -n 20 --no-pager; die "$unit did not start"; }
done
MAIN_SOCKET=$("$NODE_ROOT/bin/node" -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).socketPath)' /etc/boujot-isolator/config.json)
"$NODE_ROOT/bin/node" "$INSTALLER_DIR/check-runtime-start.mjs" "$MAIN_SOCKET" \
  || die "installed runtime startup check failed; leave the daemon stopped and inspect the package"
echo "installed: $UNITS (socket group $GROUP)"
