#!/bin/bash
# CapaCloud provider installer (activity 11). The provider page shows the one command:
#
#   curl -fsSL https://get.capa.cloud | sudo bash -s -- --token <one-time token>
#
# What it does, in order (it stops at the first problem and changes nothing it does not need to):
#   1. checks this is Ubuntu 22.04, 24.04 or 26.04 on a 64-bit x86 machine, run as root;
#   2. downloads the agent and its release manifest, and checks the manifest's signature
#      against CapaCloud's release key (built into this script) and the file's SHA-256;
#   3. runs the agent's host check (virtualization, IOMMU, an NVIDIA GPU not driving a screen, disk);
#   4. installs WireGuard and nftables, makes this machine's WireGuard key;
#   5. creates the rental directory and keeps backup, antivirus and indexing tools out of it
#      (opening anything in it is a permanent ban; the provider terms say so);
#   6. registers the machine with the one-time token, sets up the tunnel, the network rules
#      and the agent service.
#
# Options: --token T (required)  --cp URL (default https://agent.capa.cloud)
#          --base URL (where releases live, default https://get.capa.cloud/agent)
#          --skip-host-check, --driver fake, --no-services and --allow-http are for CapaCloud's own rehearsals only.
set -euo pipefail

# CapaCloud's release public key (ed25519, PEM). Replaced by scripts/release-agent.ts when a release is built.
RELEASE_PUBLIC_KEY_PEM='-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAL8n9pWfqEL2qusqnh/LwrlYKZqbGzcaQSxDgnoNt4/Q=
-----END PUBLIC KEY-----'

PROTO="=https" TOKEN="" CP="https://agent.capa.cloud" BASE="https://agent.capa.cloud/get/agent" DRIVER="linux-microvm" SKIP_HOST_CHECK=0 NO_SERVICES=0
GUEST_PRODUCT=capacloud-guest   # --debug-image: capacloud-guest-debug (test rigs only)
# The VM software, pinned and checked against these SHA-256 sums (activity 9, docs/spikes/passthrough.md).
CH_URL="https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/v54.1/cloud-hypervisor-static"
CH_SHA="f9ffb9646783233d1f0fb09e77db1fca66499d1041e63bc011b90683c0d49933"
FW_URL="https://github.com/cloud-hypervisor/edk2/releases/download/ch-97eeb7b09/CLOUDHV.fd"
FW_SHA="dc2fc8f0e43b96712d9fccc52a3a590769606412b3e1bc911d217addd3bef624"
LIB=/usr/local/lib/capacloud
IMAGES=/var/lib/capacloud/images
RENTALS=/var/lib/capacloud/rentals

say()  { printf '\033[1m%s\033[0m\n' "$*"; }
warn() { printf '\033[33mWarning: %s\033[0m\n' "$*" >&2; }
fail() { printf '\033[31mStopped: %s\033[0m\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="${2:-}"; shift 2 ;;
    --cp) CP="${2:-}"; shift 2 ;;
    --base) BASE="${2:-}"; shift 2 ;;
    --driver) DRIVER="${2:-}"; shift 2 ;;
    --skip-host-check) SKIP_HOST_CHECK=1; shift ;;
    --debug-image) GUEST_PRODUCT=capacloud-guest-debug; shift ;; # CapaCloud's test rigs only
    --no-services) NO_SERVICES=1; shift ;;   # rehearsals in a container (no systemd)
    --allow-http) PROTO='=http,https'; shift ;; # rehearsals against a local test server only
    *) fail "unknown option $1" ;;
  esac
done

# ── 1. The machine ──
[ "$(id -u)" = 0 ] || fail "run this with sudo."
[ -n "$TOKEN" ] || fail "the install token is missing: copy the whole command from your provider page."
[[ "$TOKEN" =~ ^cit_[A-Za-z0-9_-]{20,64}$ ]] || fail "that install token does not look right: copy it again from your provider page."
. /etc/os-release
case "${ID:-}-${VERSION_ID:-}" in ubuntu-22.04|ubuntu-24.04|ubuntu-26.04) ;; *) fail "CapaCloud needs Ubuntu 22.04, 24.04 or 26.04 (this is ${PRETTY_NAME:-unknown})." ;; esac
[ "$(uname -m)" = x86_64 ] || fail "CapaCloud needs a 64-bit x86 machine."
[ -e /var/lib/capacloud/agent.json ] && fail "this machine is already registered. To start again, run: sudo systemctl stop capacloud-agent; sudo rm /var/lib/capacloud/agent.json"

say "Installing the tools CapaCloud needs (curl, OpenSSL, WireGuard, nftables)…"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl ca-certificates openssl wireguard-tools nftables pciutils dosfstools mtools openssh-client zstd >/dev/null

# ── 2. The agent, checked against CapaCloud's release key ──
WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
say "Downloading the CapaCloud agent and checking its signature…"
curl -fsSL --proto "$PROTO" "$BASE/latest.json" -o "$WORK/latest.json" || fail "could not reach $BASE"
field() { sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p" "$WORK/latest.json" | head -n1; }
VERSION=$(field version); URL=$(field url); SHA=$(field sha256); SIG=$(field signature)
[[ "$VERSION" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]] || fail "the release manifest is damaged (version)."
[[ "$SHA" =~ ^[0-9a-f]{64}$ ]] || fail "the release manifest is damaged (checksum)."
printf '%s' "$RELEASE_PUBLIC_KEY_PEM" > "$WORK/release.pem"
printf 'capacloud-agent\n%s\n%s' "$VERSION" "$SHA" > "$WORK/signed.txt"
printf '%s' "$SIG" | base64 -d > "$WORK/sig.bin" 2>/dev/null || fail "the release signature is damaged."
openssl pkeyutl -verify -pubin -inkey "$WORK/release.pem" -rawin -in "$WORK/signed.txt" -sigfile "$WORK/sig.bin" >/dev/null 2>&1 \
  || fail "the release is NOT signed by CapaCloud. Nothing was installed. Please tell support@capa.cloud."
curl -fsSL --proto "$PROTO" "$URL" -o "$WORK/capacloud-agent" || fail "could not download the agent"
echo "$SHA  $WORK/capacloud-agent" | sha256sum -c --quiet - 2>/dev/null || fail "the download does not match the signed release. Nothing was installed."
install -m 755 "$WORK/capacloud-agent" /usr/local/bin/capacloud-agent
say "Agent $VERSION installed (signature checked)."

# ── 2b. The VM software (Cloud Hypervisor and its firmware), pinned by checksum ──
if [ "$DRIVER" = linux-microvm ]; then
  say "Installing the VM software (Cloud Hypervisor)…"
  install -d -m 755 "$LIB"
  getpinned() { # getpinned <url> <sha256> <destination>
    curl -fsSL --proto "$PROTO" "$1" -o "$WORK/pinned" || fail "could not download $1"
    echo "$2  $WORK/pinned" | sha256sum -c --quiet - 2>/dev/null || fail "$1 does not match its known checksum. Nothing more was installed."
    install -m 755 "$WORK/pinned" "$3"
  }
  getpinned "$CH_URL" "$CH_SHA" "$LIB/cloud-hypervisor"
  getpinned "$FW_URL" "$FW_SHA" "$LIB/CLOUDHV.fd"

  # ── 2c. The GPU, kept for rentals: vfio-pci claims it at boot, nouveau never loads ──
  # (Written without pipelines or "&&" chains at the end of loops: this script stops at the first
  # failing command, and a loop's last test counts as its result.)
  : > "$WORK/vfio.rules"
  GPU_NOW=""
  for dev in /sys/bus/pci/devices/*; do
    if [ "$(cat "$dev/vendor" 2>/dev/null)" != 0x10de ]; then continue; fi
    case "$(cat "$dev/class" 2>/dev/null)" in 0x03*) ;; *) continue ;; esac
    if [ "$(cat "$dev/boot_vga" 2>/dev/null)" = 1 ]; then continue; fi   # never the GPU driving the screen
    for member in "$dev"/iommu_group/devices/*; do
      v=$(cat "$member/vendor"); d=$(cat "$member/device")
      echo "ACTION==\"add\", SUBSYSTEM==\"pci\", ATTR{vendor}==\"$v\", ATTR{device}==\"$d\", ATTR{driver_override}=\"vfio-pci\"" >> "$WORK/vfio.rules"
    done
    if [ -z "$GPU_NOW" ]; then
      GPU_NOW=$(basename "$(readlink "$dev/driver" 2>/dev/null || echo none)")
    fi
  done
  if [ -s "$WORK/vfio.rules" ]; then
    sort -u "$WORK/vfio.rules" > /etc/udev/rules.d/60-capacloud-vfio.rules
    chmod 644 /etc/udev/rules.d/60-capacloud-vfio.rules
    echo vfio-pci > /etc/modules-load.d/capacloud-vfio.conf
    printf 'blacklist nouveau\noptions nouveau modeset=0\n' > /etc/modprobe.d/capacloud-vfio.conf
    if command -v update-initramfs >/dev/null; then update-initramfs -u >/dev/null 2>&1 || true; fi
  fi
  if [ "$GPU_NOW" != vfio-pci ] && [ "$SKIP_HOST_CHECK" = 0 ]; then
    fail "the GPU is now set aside for rentals, but another driver (${GPU_NOW:-none}) still holds it. Restart this computer once, then run the same command again (the token is still valid)."
  fi

  # ── 2d. The guest image (the system inside every rental VM), checked against the release key ──
  GBASE="${BASE%/agent}/guest"; GMANIFEST=guest-latest.json
  [ "$GUEST_PRODUCT" = capacloud-guest-debug ] && GMANIFEST=guest-debug-latest.json
  say "Downloading the rental system image and checking its signature (about 1.6 GB)…"
  curl -fsSL --proto "$PROTO" "$GBASE/$GMANIFEST" -o "$WORK/guest.json" || fail "could not reach $GBASE"
  gfield() { sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p" "$WORK/guest.json" | head -n1; }
  GP=$(gfield product); GV=$(gfield version); GF=$(gfield file); GS=$(gfield sha256); GSIG=$(gfield signature)
  [ "$GP" = "$GUEST_PRODUCT" ] || fail "the image manifest is for '$GP', not $GUEST_PRODUCT."
  [[ "$GV" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && "$GS" =~ ^[0-9a-f]{64}$ && "$GF" =~ ^[A-Za-z0-9._-]+$ ]] || fail "the image manifest is damaged."
  printf '%s\n%s\n%s' "$GP" "$GV" "$GS" > "$WORK/gsigned.txt"
  printf '%s' "$GSIG" | base64 -d > "$WORK/gsig.bin" 2>/dev/null || fail "the image signature is damaged."
  openssl pkeyutl -verify -pubin -inkey "$WORK/release.pem" -rawin -in "$WORK/gsigned.txt" -sigfile "$WORK/gsig.bin" >/dev/null 2>&1 \
    || fail "the rental system image is NOT signed by CapaCloud. Nothing more was installed."
  install -d -m 700 "$IMAGES"
  if [ "$(cat "$IMAGES/capacloud-guest.version" 2>/dev/null)" != "$GP $GV $GS" ]; then
    curl -fsSL --proto "$PROTO" "$GBASE/$GF" -o "$IMAGES/download.zst" || fail "could not download the image"
    echo "$GS  $IMAGES/download.zst" | sha256sum -c --quiet - 2>/dev/null || { rm -f "$IMAGES/download.zst"; fail "the image does not match its signed checksum."; }
    zstd -q -d -f "$IMAGES/download.zst" -o "$IMAGES/capacloud-guest.raw" && rm -f "$IMAGES/download.zst"
    echo "$GP $GV $GS" > "$IMAGES/capacloud-guest.version"
  fi
  say "Rental system image $GV ready (signature checked)."
  if [ "$GUEST_PRODUCT" = capacloud-guest-debug ]; then
    install -d -m 700 /etc/capacloud
    printf '{ "consoleLog": true }\n' > /etc/capacloud/microvm.json
  fi
fi

# ── 3. Host check ──
if [ "$SKIP_HOST_CHECK" = 0 ]; then
  say "Checking this machine (virtualization, IOMMU, GPU, disk)…"
  if ! /usr/local/bin/capacloud-agent check > "$WORK/check.json"; then
    cat "$WORK/check.json" >&2
    fail "this machine cannot be used yet. Fix the items under \"failed\" above and run the command again."
  fi
fi

# ── 4. WireGuard key (the private key never leaves this machine) ──
# Under /etc/wireguard: Ubuntu's AppArmor profile for `wg` refuses keys anywhere else
# (found on Ubuntu 26.04, 2026-11-24). A key left at the old place is moved.
install -d -m 700 /etc/capacloud /etc/wireguard
WG_KEY=/etc/wireguard/capacloud.key
if [ ! -s "$WG_KEY" ] && [ -s /etc/capacloud/wg.key ]; then install -m 600 /etc/capacloud/wg.key "$WG_KEY" && rm -f /etc/capacloud/wg.key; fi
if [ ! -s "$WG_KEY" ]; then (umask 077; wg genkey > "$WG_KEY"); fi
WG_PUB=$(wg pubkey < "$WG_KEY")

# ── 5. Rental directory, kept away from backup, antivirus and indexing tools ──
install -d -m 700 /var/lib/capacloud "$RENTALS"
# Backup tools that honour the cache-directory tag (borg, restic, tar, duplicity, many others).
printf 'Signature: 8a477f597d28d172789f06886806bc55\n# CapaCloud rentals: never back up, scan or index this directory.\n' > "$RENTALS/CACHEDIR.TAG"
touch "$RENTALS/.nomedia" "$RENTALS/.trackerignore" "$RENTALS/.nobackup"
# locate / updatedb
if [ -f /etc/updatedb.conf ] && ! grep -q "/var/lib/capacloud" /etc/updatedb.conf; then
  sed -i 's|^PRUNEPATHS="\(.*\)"|PRUNEPATHS="\1 /var/lib/capacloud"|' /etc/updatedb.conf
fi
# ClamAV daemon
for f in /etc/clamav/clamd.conf; do
  [ -f "$f" ] && ! grep -q "capacloud" "$f" && printf 'ExcludePath ^/var/lib/capacloud/\n' >> "$f" && systemctl try-restart clamav-daemon 2>/dev/null || true
done
# Timeshift
if [ -f /etc/timeshift/timeshift.json ] && ! grep -q capacloud /etc/timeshift/timeshift.json; then
  sed -i 's|"exclude" *: *\[|"exclude" : [ "/var/lib/capacloud/**",|' /etc/timeshift/timeshift.json || true
fi
# Tools this script cannot configure for you: warn, so you exclude the directory yourself.
for tool in deja-dup duplicity rsnapshot restic borg borgmatic backintime baloo_file tracker3 bacula-fd urbackupclientbackend veeamservice; do
  if command -v "$tool" >/dev/null 2>&1 || pgrep -x "$tool" >/dev/null 2>&1; then
    warn "$tool is installed. Exclude /var/lib/capacloud from it yourself: if it reads a rental's decoy files, your account is banned automatically."
  fi
done

# ── 6. Register, tunnel, network rules, service ──
say "Registering this machine with CapaCloud…"
/usr/local/bin/capacloud-agent register -token "$TOKEN" -cp "$CP" -driver "$DRIVER" -wireguard-public-key "$WG_PUB" >/dev/null \
  || fail "registration was refused. Get a new install token from your provider page and run the command again."
if /usr/local/bin/capacloud-agent wg-config > "$WORK/capacloud.conf" 2>/dev/null; then
  install -m 600 "$WORK/capacloud.conf" /etc/wireguard/capacloud.conf
else
  warn "no tunnel was assigned yet; SSH to rentals will not work until it is."
fi
install -d -m 755 /etc/nftables.d
cat > /etc/nftables.d/capacloud.nft <<'NFT'
#!/usr/sbin/nft -f
# Rental network rules on a provider's machine (brief: "Layers per rental", 4. Network).
# Installed by deploy/agent/install.sh as /etc/nftables.d/capacloud.nft and loaded at boot.
#
# Every rental VM sits on the bridge capbr0. From it:
#   - outbound TCP/UDP to the internet is allowed;
#   - private networks (RFC 1918), link-local, CGNAT, loopback and multicast are blocked:
#     the renter can never reach the provider's home network or other devices;
#   - port 25 (email) is blocked;
#   - nothing from the bridge may reach this machine itself (no host services at all);
#   - the only way IN is SSH from the CapaCloud gateway over the WireGuard tunnel (capacloud),
#     to the rental's own port.
# Blocked packets are counted and logged with a "capacloud-block" prefix, which the agent reads
# to report egress_blocked / smtp_attempt events (amber).
#
# Only the table "capacloud" is touched: the provider's own firewall rules stay as they are.

table inet capacloud
delete table inet capacloud

table inet capacloud {
	set blocked4 {
		type ipv4_addr; flags interval
		elements = { 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12,
		             192.0.0.0/24, 192.168.0.0/16, 198.18.0.0/15, 224.0.0.0/3 }
	}
	set blocked6 {
		type ipv6_addr; flags interval
		elements = { ::/127, ::ffff:0:0/96, 64:ff9b::/96, fc00::/7, fe80::/10, ff00::/8 }
	}

	# Nothing from a rental reaches this machine itself. Only replies to connections THIS machine
	# opened (the agent checking its own VMs) come back; a rental cannot open one.
	chain input {
		type filter hook input priority filter - 10; policy accept;
		iifname "capbr0" ct state established,related accept
		iifname "capbr0" counter log prefix "capacloud-block host " drop
	}

	chain forward {
		type filter hook forward priority filter - 10; policy accept;
		# TCP through the CapaCloud tunnel fits the tunnel's packets (MSS clamping): the rental's
		# 1460-byte segments otherwise stalled SSH sessions from the gateway (2026-11-24).
		oifname "capacloud" tcp flags syn tcp option maxseg size set rt mtu
		iifname "capacloud" tcp flags syn tcp option maxseg size set rt mtu
		# Replies to connections the rental opened.
		iifname "capbr0" ct state established,related accept
		# Email (port 25) is blocked for every destination.
		iifname "capbr0" tcp dport 25 counter log prefix "capacloud-block smtp " drop
		# The provider's home network and other private ranges.
		iifname "capbr0" ip daddr @blocked4 counter log prefix "capacloud-block private " drop
		iifname "capbr0" ip6 daddr @blocked6 counter log prefix "capacloud-block private " drop
		# Everything else to the internet: allowed (new connections only from the rental).
		iifname "capbr0" oifname != "capbr0" accept
		# Into a rental: only SSH from the CapaCloud tunnel, and replies to the rental's own connections.
		oifname "capbr0" iifname "capacloud" tcp dport 22 accept
		oifname "capbr0" ct state established,related accept
		oifname "capbr0" counter drop
	}

	# Rentals share the machine's internet address (NAT), like any device behind a router.
	chain postrouting {
		type nat hook postrouting priority srcnat; policy accept;
		iifname "capbr0" oifname != "capbr0" masquerade
	}
}
NFT
grep -q 'nftables.d' /etc/nftables.conf 2>/dev/null || printf '\ninclude "/etc/nftables.d/*.nft"\n' >> /etc/nftables.conf
# Memory protection: no program may attach to another or read its memory, root included, so a
# rental's VM memory cannot be read on this machine (attempts are logged and raise an alarm).
# Debuggers such as gdb -p stop working on this machine.
printf 'kernel.yama.ptrace_scope = 3\n' > /etc/sysctl.d/60-capacloud.conf
sysctl -q -w kernel.yama.ptrace_scope=3 2>/dev/null || warn "could not switch on memory protection (kernel.yama.ptrace_scope)."
cat > /etc/systemd/system/capacloud-agent.service <<'UNIT'
# The CapaCloud agent on a provider's machine (activity 11). Installed by deploy/agent/install.sh.
[Unit]
Description=CapaCloud agent (rents out this machine's GPU)
Wants=network-online.target wg-quick@capacloud.service
After=network-online.target wg-quick@capacloud.service nftables.service

[Service]
ExecStart=/usr/local/bin/capacloud-agent run -state /var/lib/capacloud/agent.json
Restart=always
RestartSec=5
# The agent runs VMs and reads hardware, so it runs as root; it gets no more than that.
NoNewPrivileges=yes
ProtectHome=read-only
PrivateTmp=yes
StateDirectory=capacloud
StateDirectoryMode=0700

[Install]
WantedBy=multi-user.target
UNIT

if [ "$NO_SERVICES" = 0 ]; then
  nft -f /etc/nftables.d/capacloud.nft
  # Enable for the next start only: starting nftables.service now would run /etc/nftables.conf,
  # whose "flush ruleset" also wipes other software's live rules (Tailscale, Docker).
  systemctl enable nftables >/dev/null 2>&1 || true
  [ -f /etc/wireguard/capacloud.conf ] && systemctl enable --now wg-quick@capacloud >/dev/null
  systemctl daemon-reload
  systemctl enable --now capacloud-agent >/dev/null
fi

say "Done. This machine is registered. Leave it on: after its checks and a 24-hour burn-in it is listed for rent."
say "Your provider page shows its progress."
