#!/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

# Install + start only, then exit 0 (#582 decision B). The install-mode choice
# and consent (S8) are a SEPARATE step the operator runs in this same terminal —
# 'ourcloud-agent enroll <CODE>' — so the doorway never runs a non-interactive
# consent it cannot answer (ADR 0024). The code above is validated present so the
# operator pasted the full one-liner; the consent step redeems it.
echo "ourcloud: agent installed and started. Finish founding in this terminal with:" >&2
echo "  ourcloud-agent enroll $code" >&2
