Skip to content

Self-improving AI Employees for everyone

2.6 KB
Raw Blame
#!/bin/bash
# OpenCompany EC2 startup script (cloud-init user_data, rendered by Terraform
# `templatefile`). Runs once as root on first boot.
#
# Installs OpenCompany the documented way -- the repo's install.sh, run as the
# login user, never root -- then writes the login-gate env file and runs
# `company serve` under systemd as that user. A root install leaves the venvs
# and ~/.opencompany owned by root (docs-internal/errors.md #16).
#
# NOTE on syntax: Terraform renders this file with templatefile(), so any
# dollar-brace sequence is a Terraform interpolation. Bash variables are
# therefore written UNBRACED ($APP_USER, $APP_HOME). `set -x` is intentionally
# NOT used so secrets in the env file are never echoed to the console log.
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

APP_USER=ubuntu
APP_HOME=/home/$APP_USER
INSTALL_SH='${install_sh_url}'

echo "[${resource_name}] installing OpenCompany as $APP_USER..."
sudo -u $APP_USER -H env OPENCOMPANY_VERSION="${version}" \
  bash -c "curl -fsSL $INSTALL_SH | bash"

echo "[${resource_name}] writing login-gate env..."
mkdir -p /etc/${resource_name}
cat > /etc/${resource_name}/opencompany.env <<'OPENCOMPANY_ENV_EOF'
%{ for k, v in app_env ~}
${k}=${v}
%{ endfor ~}
OPENCOMPANY_ENV_EOF
chmod 600 /etc/${resource_name}/opencompany.env

# DATA_DIR from app_env (/var/lib/<resource_name>) must be writable by the
# service user.
mkdir -p /var/lib/${resource_name}
chown $APP_USER:$APP_USER /var/lib/${resource_name}

echo "[${resource_name}] installing systemd service..."
# The shim lives under the user's bun global bin dir (install.sh installs bun
# for the login user; BUN_INSTALL defaults to ~/.bun).
OPENCOMPANY_BIN="$APP_HOME/.bun/bin/company"
test -x "$OPENCOMPANY_BIN"
cat > /etc/systemd/system/${resource_name}.service <<SERVICE_EOF
[Unit]
Description=OpenCompany (single login-gated instance)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$APP_USER
WorkingDirectory=$APP_HOME
Environment=PATH=$APP_HOME/.bun/bin:$APP_HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=/etc/${resource_name}/opencompany.env
ExecStart=$OPENCOMPANY_BIN serve
Restart=on-failure
RestartSec=5
# Must outlast the CLI's backend shutdown allowance with Temporal on
# (backend_shutdown_grace_seconds in cli/_common.py), or systemd kills the
# backend before it records a clean shutdown. cli/tests/test_backend_shutdown.py
# checks it.
TimeoutStopSec=150

[Install]
WantedBy=multi-user.target
SERVICE_EOF

systemctl daemon-reload
systemctl enable --now ${resource_name}
echo "[${resource_name}] OpenCompany is ready."