#!/bin/sh
# The OurCloud install command (ADR 0054) — a doorway, not a kept tool (ADR 0028).
# Usage: curl -sSf https://get.idss.nz | sh -s -- <ENROLLMENT-CODE>
set -e

code="$1"
if [ -z "$code" ]; then
	echo "ourcloud: no enrollment code — run the one-liner your operator gave you: curl -sSf https://get.idss.nz | sh -s -- <CODE>" >&2
	exit 2
fi

arch="$(uname -m)"
if [ "$arch" != "x86_64" ]; then
	echo "ourcloud: founding a machine supports x86_64 only at v1; this machine reports $arch (ADR 0024)" >&2
	exit 3
fi

bin="/usr/local/bin/ourcloud-agent"
unit="/etc/systemd/system/ourcloud-agent.service"

echo "ourcloud: fetching the community's pinned agent from get.idss.nz…" >&2
curl -sSf "https://get.idss.nz/get?arch=x86_64" -o "$bin"
chmod 0755 "$bin"

# Lay down the standing agent as a persistent OS service — enabled at boot and
# started now — so the join and everything after it outlive this terminal (ADR
# 0053). This is byte-for-byte the unit internal/install's Service adapter writes.
cat > "$unit" <<'UNIT'
[Unit]
Description=OurCloud agent (ADR 0053)
After=network-online.target

[Service]
ExecStart=/usr/local/bin/ourcloud-agent join
Restart=always

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now ourcloud-agent.service

# Hand the code to the standing agent in the FOREGROUND: the install-mode choice
# and consent (S8) render in the operator's own terminal (ADR 0024). exec so the
# doorway leaves nothing of itself behind (ADR 0028).
exec "$bin" enroll "$code"
