#!/usr/bin/env bash
# Minimal installer for renboot-agent (Tier 5).
# Creates the 'renboot' system user the unit assumes.
# Usage: curl ... | sh   or  bash install-headless.sh /path/to/renboot-agent
set -euo pipefail

BIN_SRC="${1:-./renboot-agent}"
INSTALL_DIR="/usr/local/bin"
USER="renboot"
UNIT_DIR="/etc/systemd/system"

if ! id -u "$USER" >/dev/null 2>&1; then
  useradd --system --no-create-home --shell /usr/sbin/nologin "$USER" || true
fi

install -m 0755 -o root -g root "$BIN_SRC" "$INSTALL_DIR/renboot-agent"

# Provide a unit template (copy/adapt scripts/renboot-headless-agent.service).
# Move to Type=notify + WatchdogSec=30s in real unit for sd_notify support.
cat > /tmp/renboot-headless-agent.service << 'EOF'
[Unit]
Description=Renboot Headless Provider Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
User=renboot
ExecStart=/usr/local/bin/renboot-agent run
Restart=always
RestartSec=5
WatchdogSec=30s
# Environment=ORCHESTRATOR_URL=... RENBOOT_DEVICE_ID=... etc

[Install]
WantedBy=multi-user.target
EOF

echo "Installed. Enable with: sudo cp /tmp/renboot-headless-agent.service $UNIT_DIR/ && sudo systemctl daemon-reload && sudo systemctl enable --now renboot-headless-agent"
echo "Note: update unit with real ORCHESTRATOR_URL + tokens (or use env file)."
