#!/bin/bash
set -e
echo "🚀 Starting Cortex Agent Provisioning for node: {{ node_id }}"
# Determine OS and Arch
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
if [ "$ARCH" = "x86_64" ]; then
ARCH="amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
ARCH="arm64"
fi
if [ "$OS" = "darwin" ]; then
# Currently fallback to python method or generic binary if available
# For now assume arm64 if darwin and M1
if [ "$ARCH" = "amd64" ]; then
BIN_ARCH="darwin_amd64"
else
BIN_ARCH="darwin_arm64"
fi
else
BIN_ARCH="${OS}_${ARCH}"
fi
# 1. Create .cortex/agent-node directory
INSTALL_DIR="$HOME/.cortex/agent-node"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
# 2. Write agent_config.yaml
echo "[*] Writing configuration..."
cat > agent_config.yaml << 'EOF'
{{ config_yaml }}
EOF
# 3. Download standalone binary
echo "[*] Downloading unified binary core for $BIN_ARCH..."
INSTALLER_URL="{{ base_url }}/api/v1/agent/binary/$BIN_ARCH"
if ! curl -sSLf "$INSTALLER_URL" -o cortex-agent; then
echo "❌ Failed to download binary for architecture: $BIN_ARCH from $INSTALLER_URL"
echo "Fallback: Try the python headless installer instead: curl -sSL {{ base_url }}/api/v1/nodes/provision/{{ node_id }} | python3"
exit 1
fi
chmod +x cortex-agent
# 4. Bootstrap daemon installation
echo "[*] Bootstrapping agent daemon..."
# Run the standalone binary with the install-daemon flags (must implement in main.py)
# Or we can just run it in the background if systemd is unavailable
systemctl --user list-units >/dev/null 2>&1 && HAS_SYSTEMD=true || HAS_SYSTEMD=false
if [ "$HAS_SYSTEMD" = true ]; then
echo "Installing Linux systemd user service..."
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/cortex-agent.service << EOF
[Unit]
Description=Cortex Agent Node
After=network.target
[Service]
Type=simple
ExecStart=$INSTALL_DIR/cortex-agent
WorkingDirectory=$INSTALL_DIR
Restart=always
RestartSec=5
StandardOutput=append:$HOME/.cortex/agent.out.log
StandardError=append:$HOME/.cortex/agent.err.log
[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable cortex-agent
systemctl --user restart cortex-agent
loginctl enable-linger "$USER" 2>/dev/null || true
echo "✅ Systemd Daemon successfully started!"
else
echo "Systemd not available. Falling back to background loop (nohup)..."
nohup ./cortex-agent >> "$HOME/.cortex/agent.out.log" 2>&1 &
echo $! > agent.pid
echo "✅ Background Agent started (PID $!)"
fi
echo "✅ Provisioning complete! Node should be online in the Mesh Dashboard shortly."