#!/usr/bin/env bash
# Boxmind agent installer. Usage: curl -fsSL https://jetstack.sh/install.sh | bash -s -- <install-token>
# What it does: installs one binary and one systemd service. It opens no ports;
# the agent only makes outgoing HTTPS requests to https://jetstack.sh.
set -euo pipefail
TOKEN="${1:-}"
BASE="${JETSTACK_URL:-https://jetstack.sh}"
if [ -z "$TOKEN" ]; then echo "usage: curl -fsSL https://jetstack.sh/install.sh | bash -s -- <install-token>" >&2; exit 1; fi
if [ "$(id -u)" != "0" ]; then echo "Please run as root (prefix with sudo)." >&2; exit 1; fi
case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "Unsupported CPU: $(uname -m)" >&2; exit 1 ;;
esac
echo "==> Boxmind: installing the agent ($ARCH)"
mkdir -p /etc/jetstack /srv/projects /var/lib/jetstack/snapshots /var/log/jetstack
chmod 700 /etc/jetstack /var/log/jetstack
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
curl -fsSL --retry 5 --retry-all-errors "$BASE/dl/jetstack-agent-linux-$ARCH" -o "$TMP"
WANT="$(curl -fsSL --retry 5 --retry-all-errors "$BASE/dl/jetstack-agent-linux-$ARCH.sha256" | cut -d' ' -f1)"
GOT="$(sha256sum "$TMP" | cut -d' ' -f1)"
if [ "$WANT" != "$GOT" ]; then echo "Download check failed (expected $WANT, got $GOT). Nothing was installed." >&2; exit 1; fi
install -m 0755 "$TMP" /usr/local/bin/jetstack-agent
if ! command -v git >/dev/null 2>&1; then
  echo "==> Installing git"
  if command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq git >/dev/null
  elif command -v dnf >/dev/null 2>&1; then dnf install -y -q git
  elif command -v apk >/dev/null 2>&1; then apk add -q git; fi
fi
JETSTACK_TOKEN="$TOKEN" /usr/local/bin/jetstack-agent register --url "$BASE"
cat >/etc/systemd/system/jetstack-agent.service <<'UNIT'
[Unit]
Description=Boxmind agent
After=network-online.target
Wants=network-online.target
# Never give up restarting: a server that is not connected cannot be helped.
StartLimitIntervalSec=0

[Service]
ExecStart=/usr/local/bin/jetstack-agent run
Restart=always
RestartSec=2
# Exit status 3 means the server was disconnected from Boxmind: stay stopped.
RestartPreventExitStatus=3
# The agent pings the watchdog only while its connections are healthy; if it
# hangs, systemd restarts it.
WatchdogSec=120
NotifyAccess=main
Environment=HOME=/root

[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable jetstack-agent >/dev/null
systemctl restart jetstack-agent
echo "==> Done. This server is connected to Boxmind. No ports were opened."
echo "    Every command Boxmind runs is logged on this server: /var/log/jetstack/audit.log"
echo "    Disconnect at any time: systemctl disable --now jetstack-agent && rm -rf /usr/local/bin/jetstack-agent /etc/jetstack"
