#!/bin/sh
# © Black Well Foundry LLC. All rights reserved. Published so you can read
# what ServerMage runs on your server (https://servermage.app/your-server).
#
# ServerMage host setup (spec §6.1 steps 5–7, decisions P0-010, P0-012).
#
# Run as root over the bootstrap SSH session, after the user approved the plan
# built from inspect.sh:
#
#     sudo sh -s -- --agent-image REF [options] < install.sh
#
# Options:
#   --agent-image REF       Agent image to run (repo@sha256:… from the signed
#                           catalog). Required unless --only-docker.
#   --only-docker           Stop after Docker is installed and running.
#   --replace-conflicting-packages
#                           On Rocky/Alma, allow dnf to remove packages that
#                           conflict with Docker (podman, buildah, runc).
#   --no-firewall           Don't open the Agent and Bonjour ports.
#
# Idempotent: re-running keeps Docker, the Agent's data and its identity, and
# issues a fresh pairing token. That is the re-pair path (P0-001).
#
# Output: one JSON object per line on stdout. Progress events look like
#   {"event":"step","step":"docker","state":"running","message":"…"}
# with state running | succeeded | skipped | failed (the API's step states)
# and the last line is the result:
#   {"event":"result","ok":true,"agent":{…},"pairing":{…pairing.json…}}
#   {"event":"result","ok":false,"code":"…","message":"…","step":"…"}
# Command output goes to stderr. Exit status: 0 ok, 1 failed, 2 usage.

set -u
LC_ALL=C
export LC_ALL
SCRIPT_VERSION="1.2.0"
AGENT_PORT=47800
AGENT_NAME=servermage-agent
SM_DIR=/opt/servermage
# Present when setup opened mDNS in the firewall; holds ufw or firewalld.
MDNS_MARKER=$SM_DIR/config/firewall-mdns

# Docker's repository signing keys (verified 2026-10-04). Pinned so a
# compromised mirror or MITM can't substitute its own key (threat model M-03).
DOCKER_DEB_KEY_FPR=9DC858229FC7DD38854AE2D88D81803C0EBFCD88
DOCKER_RPM_KEY_FPR=060A61C51B558A7F742B77AAC52FEB6B621E9F35

# ---------------------------------------------------------------- output

js() {
	printf '%s' "$1" | tr -d '\000-\010\013\014\016-\037' | awk '
		BEGIN { ORS = ""; printf "\"" }
		{
			gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); gsub(/\r/, "\\r")
			if (NR > 1) printf "\\n"
			printf "%s", $0
		}
		END { printf "\"" }'
}

CURRENT_STEP=""
step() { # step NAME STATE [MESSAGE]
	CURRENT_STEP=$1
	printf '{"event":"step","step":%s,"state":%s,"message":%s}\n' "$(js "$1")" "$(js "$2")" "$(js "${3:-}")"
}

fail() { # fail CODE MESSAGE
	step "$CURRENT_STEP" failed "$2"
	printf '{"event":"result","ok":false,"code":%s,"message":%s,"step":%s}\n' "$(js "$1")" "$(js "$2")" "$(js "$CURRENT_STEP")"
	exit 1
}

log() { printf '%s\n' "$*" >&2; }

# run CMD…: run a command with its output on stderr.
run() { "$@" >&2; }

have() { command -v "$1" >/dev/null 2>&1; }

# newer A B: version A sorts after version B.
newer() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }

# ---------------------------------------------------------------- arguments

AGENT_IMAGE="" ONLY_DOCKER=0 REPLACE_CONFLICTS=0 FIREWALL=1
while [ $# -gt 0 ]; do
	case "$1" in
	--agent-image)
		[ $# -ge 2 ] || { echo "--agent-image needs a value" >&2; exit 2; }
		AGENT_IMAGE=$2
		shift 2
		;;
	--only-docker) ONLY_DOCKER=1; shift ;;
	--replace-conflicting-packages) REPLACE_CONFLICTS=1; shift ;;
	--no-firewall) FIREWALL=0; shift ;;
	*) echo "unknown option: $1" >&2; exit 2 ;;
	esac
done
if [ "$ONLY_DOCKER" -eq 0 ] && [ -z "$AGENT_IMAGE" ]; then
	echo "--agent-image is required" >&2
	exit 2
fi
# Image references come from the signed catalog, but validate the shape
# anyway: they end up in a command line.
case "$AGENT_IMAGE" in
*[!A-Za-z0-9._:/@-]*) echo "invalid --agent-image" >&2; exit 2 ;;
esac

# ---------------------------------------------------------------- preflight

step preflight running
[ "$(id -u)" -eq 0 ] || fail not_root "Setup must run as root (through sudo)."
[ -d /run/systemd/system ] || fail no_systemd "ServerMage needs a systemd-based OS."
ID="" VERSION_ID="" VERSION_CODENAME="" PRETTY_NAME=""
# shellcheck disable=SC1091
[ -r /etc/os-release ] && . /etc/os-release
MAJOR=${VERSION_ID%%.*}
case "$ID:$VERSION_ID" in
ubuntu:22.04 | ubuntu:24.04 | ubuntu:26.04 | debian:12 | debian:13) FAMILY=debian ;;
rocky:9* | rocky:10* | almalinux:9* | almalinux:10*) FAMILY=rhel ;;
*) fail os_unsupported "${PRETTY_NAME:-This OS} isn't supported by ServerMage." ;;
esac
case "$(uname -m)" in
x86_64 | aarch64) ;;
*) fail arch_unsupported "CPU architecture $(uname -m) isn't supported." ;;
esac
if have docker && docker --version 2>/dev/null | grep -qi podman; then
	fail podman_docker "The docker command on this server is Podman. ServerMage 1.0 needs Docker Engine."
fi
step preflight succeeded "$PRETTY_NAME, $(uname -m)"

# ---------------------------------------------------------------- docker

# verify_key FILE FINGERPRINT: the key file's primary fingerprint must match.
verify_key() {
	got=$(gpg --batch --show-keys --with-colons "$1" 2>/dev/null | awk -F: '/^fpr/ { print $10; exit }')
	[ "$got" = "$2" ] || fail docker_key_mismatch "Docker's repository key fingerprint didn't match (got ${got:-nothing}). Setup stopped to protect the server."
}

install_docker_debian() {
	export DEBIAN_FRONTEND=noninteractive
	run apt-get update -q || fail docker_install_failed "Couldn't update the package lists."
	run apt-get install -y -q ca-certificates curl gnupg || fail docker_install_failed "Couldn't install curl and gnupg."
	tmp=$(mktemp)
	curl -fsSL --retry 3 "https://download.docker.com/linux/$ID/gpg" -o "$tmp" ||
		fail repo_unreachable "Couldn't download Docker's repository key."
	verify_key "$tmp" "$DOCKER_DEB_KEY_FPR"
	install -d -m 0755 /etc/apt/keyrings
	install -m 0644 "$tmp" /etc/apt/keyrings/docker.asc
	rm -f "$tmp"
	echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable" \
		>/etc/apt/sources.list.d/docker.list
	run apt-get update -q || fail docker_install_failed "Couldn't read Docker's package repository."
	run apt-get install -y -q docker-ce docker-ce-cli containerd.io ||
		fail docker_install_failed "Installing Docker failed. See the diagnostics for the package manager's output."
}

install_docker_rhel() {
	have gpg || run dnf install -y -q gnupg2 || fail docker_install_failed "Couldn't install gnupg2."
	tmp=$(mktemp)
	curl -fsSL --retry 3 https://download.docker.com/linux/rhel/gpg -o "$tmp" ||
		fail repo_unreachable "Couldn't download Docker's repository key."
	verify_key "$tmp" "$DOCKER_RPM_KEY_FPR"
	install -m 0644 "$tmp" /etc/pki/rpm-gpg/docker-ce.asc
	rm -f "$tmp"
	rpm --import /etc/pki/rpm-gpg/docker-ce.asc
	cat >/etc/yum.repos.d/docker-ce.repo <<EOF
[docker-ce-stable]
name=Docker CE Stable - \$basearch
baseurl=https://download.docker.com/linux/rhel/$MAJOR/\$basearch/stable
enabled=1
gpgcheck=1
repo_gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/docker-ce.asc
EOF
	# Ask dnf what the install would take away before doing it. Packages go
	# two ways: listed under "Removing" (conflicts, needs --allowerasing) or
	# as "replacing <pkg>" under "Installing" (obsoletes: containerd.io
	# obsoletes runc, which plain `dnf install` would do silently). Podman
	# usually stays, since it uses crun. Never remove anything unapproved.
	removals=$(dnf install --assumeno --allowerasing docker-ce docker-ce-cli containerd.io 2>/dev/null | awk '
		/^Removing/ { r = 1; next }
		/^[^ ]/ { r = 0 }
		$1 == "replacing" { sub(/\.(x86_64|aarch64|noarch)$/, "", $2); print $2; next }
		r && NF { print $1 }' | sort -u | tr '\n' ' ')
	allow=""
	if [ -n "$removals" ]; then
		if [ "$REPLACE_CONFLICTS" -ne 1 ]; then
			# Leave the host as it was: drop the repository we just added.
			rm -f /etc/yum.repos.d/docker-ce.repo
			fail conflicting_packages "Installing Docker would remove or replace: ${removals% }. Approve replacing them to continue."
		fi
		allow=--allowerasing
	fi
	# Docker's NAT rules need netfilter modules that EL10 ships in
	# kernel-modules-extra. dnf would otherwise pull that package only for the
	# newest kernel, leaving the running one without it until a reboot. Best
	# effort: older kernels' packages may be gone from the mirrors.
	if ! rpm -q "kernel-modules-extra-$(uname -r)" >/dev/null 2>&1; then
		run dnf install -y -q "kernel-modules-extra-$(uname -r)" ||
			log "kernel-modules-extra for $(uname -r) isn't available; continuing"
	fi
	# shellcheck disable=SC2086
	run dnf install -y -q $allow docker-ce docker-ce-cli containerd.io ||
		fail docker_install_failed "Installing Docker failed. See the diagnostics for the package manager's output."
}

step docker running
if have docker; then
	step docker running "Docker is already installed; keeping it"
else
	step docker running "Installing Docker Engine from Docker's official repository"
	if [ "$FAMILY" = debian ]; then install_docker_debian; else install_docker_rhel; fi
fi
# reboot_pending: a newer kernel (or Debian's reboot flag) is waiting.
reboot_pending() {
	[ -f /var/run/reboot-required ] && return 0
	if have rpm; then
		newest=$(rpm -q --last kernel-core 2>/dev/null | head -n 1 | awk '{ print $1 }')
		[ -n "$newest" ] && [ "$newest" != "kernel-core-$(uname -r)" ] && return 0
	fi
	return 1
}
# repair_kernel_modules: on the RHEL family, a kernel update can leave the
# running kernel without kernel-modules-extra, and Docker then fails on
# missing netfilter modules (found in certification, 2026-10-05). Install
# the package for the running kernel.
repair_kernel_modules() {
	[ "$FAMILY" = rhel ] && have rpm && have journalctl || return 1
	journalctl -u docker.service --no-pager -n 80 2>/dev/null |
		grep -qiE 'missing kernel module|extension addrtype|modprobe|failed to add jump rules|RULE_APPEND failed|failed to register "bridge" driver' || return 1
	pkg="kernel-modules-extra-$(uname -r)"
	rpm -q "$pkg" >/dev/null 2>&1 && return 1
	step docker running "Installing $pkg: Docker needs its network modules for this kernel"
	run dnf install -y -q "$pkg" || return 1
	run systemctl reset-failed docker.service docker.socket
	run systemctl start docker.service
}
# A Docker that failed repeatedly is held back by systemd's start limit.
systemctl reset-failed docker.service docker.socket >/dev/null 2>&1 || true
if ! run systemctl enable --now docker.service && ! repair_kernel_modules; then
	if reboot_pending; then
		fail reboot_required "Docker is installed but needs a restart of the server to load an updated kernel. Restart the server, then run setup again."
	fi
	run journalctl -u docker.service --no-pager -n 20
	fail docker_start_failed "Docker is installed but wouldn't start."
fi
i=0
until docker info >/dev/null 2>&1; do
	i=$((i + 1))
	[ "$i" -lt 30 ] || fail docker_start_failed "Docker didn't become ready within 30 seconds."
	sleep 1
done
DOCKER_VERSION=$(docker version --format '{{.Server.Version}}')
dmajor=${DOCKER_VERSION%%.*}
dminor=${DOCKER_VERSION#*.}
dminor=${dminor%%.*}
if [ "$dmajor" -lt 20 ] || { [ "$dmajor" -eq 20 ] && [ "$dminor" -lt 10 ]; }; then
	fail docker_too_old "Docker $DOCKER_VERSION is too old. ServerMage needs Docker 20.10 or newer."
fi
step docker succeeded "Docker $DOCKER_VERSION"

if [ "$ONLY_DOCKER" -eq 1 ]; then
	printf '{"event":"result","ok":true,"docker_version":%s}\n' "$(js "$DOCKER_VERSION")"
	exit 0
fi

# ---------------------------------------------------------------- layout (spec §6.2)

step layout running
install -d -m 0700 -o root -g root "$SM_DIR" || fail layout_failed "Couldn't create $SM_DIR."
for d in data services backups logs config; do
	install -d -m 0700 -o root -g root "$SM_DIR/$d" || fail layout_failed "Couldn't create $SM_DIR/$d."
done
step layout succeeded "$SM_DIR"

# ---------------------------------------------------------------- firewall

step firewall running
if [ "$FIREWALL" -eq 0 ]; then
	step firewall skipped "Not changing the firewall (--no-firewall)"
elif have ufw && grep -qi '^ENABLED=yes' /etc/ufw/ufw.conf 2>/dev/null; then
	# The mDNS rule is recorded only when setup adds it, so removal never
	# closes one the server already had (uninstall.sh).
	mdns_new=1
	ufw status 2>/dev/null | grep -q '^5353/udp ' && mdns_new=0
	if ! { run ufw allow "$AGENT_PORT/tcp" comment "ServerMage Agent" &&
		run ufw allow 5353/udp comment "mDNS (ServerMage discovery)"; }; then
		fail firewall_failed "Couldn't open the Agent port in ufw."
	fi
	[ "$mdns_new" -eq 0 ] || echo ufw >"$MDNS_MARKER"
	step firewall succeeded "ufw: allowed $AGENT_PORT/tcp and 5353/udp"
elif have firewall-cmd && systemctl is-active --quiet firewalld; then
	mdns_new=1
	firewall-cmd --permanent --query-service=mdns >/dev/null 2>&1 && mdns_new=0
	if ! { run firewall-cmd --permanent --add-port="$AGENT_PORT/tcp" &&
		run firewall-cmd --permanent --add-service=mdns &&
		run firewall-cmd --reload; }; then
		fail firewall_failed "Couldn't open the Agent port in firewalld."
	fi
	[ "$mdns_new" -eq 0 ] || echo firewalld >"$MDNS_MARKER"
	step firewall succeeded "firewalld: allowed $AGENT_PORT/tcp and mDNS"
else
	step firewall skipped "No active ufw or firewalld"
fi

# ---------------------------------------------------------------- agent

step agent_image running
if docker image inspect "$AGENT_IMAGE" >/dev/null 2>&1; then
	step agent_image succeeded "Image already present"
else
	run docker pull "$AGENT_IMAGE" || fail image_pull_failed "Couldn't download the ServerMage Agent image."
	step agent_image succeeded "Downloaded"
fi
IMAGE_ID=$(docker image inspect --format '{{.Id}}' "$AGENT_IMAGE")
# Prefer the registry digest; a locally built image only has its ID.
IMAGE_DIGEST=$(docker image inspect --format '{{range .RepoDigests}}{{.}}{{"\n"}}{{end}}' "$AGENT_IMAGE" | head -n 1)
[ -n "$IMAGE_DIGEST" ] || IMAGE_DIGEST=$IMAGE_ID

step agent running
# An Agent self-update that stopped halfway (P6-006) leaves the previous
# Agent renamed and stopped: bring it back. A finished updater container
# is only kept for its log.
if ! docker inspect "$AGENT_NAME" >/dev/null 2>&1 && docker inspect "$AGENT_NAME-previous" >/dev/null 2>&1; then
	run docker rename "$AGENT_NAME-previous" "$AGENT_NAME" || fail agent_start_failed "Couldn't restore the previous Agent."
	step agent running "Restoring the Agent from an interrupted update"
fi
if [ "$(docker inspect --format '{{.State.Running}}' servermage-updater 2>/dev/null)" = false ]; then
	run docker rm servermage-updater || true
fi
current_image=$(docker inspect --format '{{.Image}}' "$AGENT_NAME" 2>/dev/null || true)
if [ -n "$current_image" ] && [ "$current_image" != "$IMAGE_ID" ]; then
	# A different Agent version is installed. A newer one (it updates
	# itself, P6-006) is kept: its database may already be in a format the
	# older one can't read. An older one is replaced; the data under
	# $SM_DIR (identity, devices, services) is kept either way.
	# The running Agent knows its version; a stopped one carries it as a
	# label (Agent 0.5.0 and later), which outlives a removed image.
	have_version=$(docker exec "$AGENT_NAME" /servermage-agent version 2>/dev/null ||
		docker inspect --format '{{index .Config.Labels "org.opencontainers.image.version"}}' "$AGENT_NAME" 2>/dev/null ||
		true)
	[ "$have_version" = "<no value>" ] && have_version=""
	[ -n "$have_version" ] ||
		have_version=$(docker run --rm --entrypoint /servermage-agent "$current_image" version 2>/dev/null || true)
	new_version=$(docker run --rm --entrypoint /servermage-agent "$AGENT_IMAGE" version 2>/dev/null || true)
	if [ -n "$have_version" ] && [ -n "$new_version" ] && newer "$have_version" "$new_version"; then
		AGENT_IMAGE=$(docker inspect --format '{{.Config.Image}}' "$AGENT_NAME")
		IMAGE_DIGEST=$(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$AGENT_NAME" | sed -n 's/^SM_IMAGE_DIGEST=//p')
		[ -n "$IMAGE_DIGEST" ] || IMAGE_DIGEST=$current_image
		step agent running "Keeping the installed Agent $have_version; it's newer than $new_version"
	else
		run docker rm -f "$AGENT_NAME" || fail agent_start_failed "Couldn't replace the existing Agent container."
		current_image=""
		step agent running "Replacing the existing Agent with the new version"
	fi
fi
if [ -z "$current_image" ]; then
	# P0-010 runtime configuration.
	run docker run -d --name "$AGENT_NAME" --restart unless-stopped \
		--network host \
		-v /var/run/docker.sock:/var/run/docker.sock \
		-v "$SM_DIR:$SM_DIR" \
		-v /:/host:ro,rslave \
		-e SM_HOST_ROOT=/host \
		-e "SM_IMAGE_DIGEST=$IMAGE_DIGEST" \
		"$AGENT_IMAGE" ||
		fail agent_start_failed "Couldn't start the ServerMage Agent."
else
	run docker start "$AGENT_NAME" || fail agent_start_failed "Couldn't start the ServerMage Agent."
fi
i=0
until docker exec "$AGENT_NAME" /servermage-agent healthcheck >/dev/null 2>&1; do
	i=$((i + 1))
	if [ "$i" -ge 60 ]; then
		run docker logs --tail 50 "$AGENT_NAME"
		fail agent_unhealthy "The ServerMage Agent didn't become healthy within 60 seconds."
	fi
	sleep 1
done
AGENT_VERSION=$(docker exec "$AGENT_NAME" /servermage-agent version)
step agent succeeded "Agent $AGENT_VERSION is running"

# ---------------------------------------------------------------- pairing (P0-001)

step pairing running
# Always mint a fresh token: covers both a new Agent and re-pairing an
# existing one. The token reaches the app only through this SSH session.
run docker exec "$AGENT_NAME" /servermage-agent pairing-token ||
	fail pairing_failed "The Agent couldn't create a pairing token."
PAIRING=$(cat "$SM_DIR/config/pairing.json") || fail pairing_failed "Couldn't read the pairing file."
step pairing succeeded "Pairing token ready (valid 15 minutes)"

printf '{"event":"result","ok":true,"script_version":%s,"docker_version":%s,"agent":{"version":%s,"image":%s,"image_digest":%s,"port":%s},"pairing":%s}\n' \
	"$(js "$SCRIPT_VERSION")" "$(js "$DOCKER_VERSION")" "$(js "$AGENT_VERSION")" "$(js "$AGENT_IMAGE")" \
	"$(js "$IMAGE_DIGEST")" "$AGENT_PORT" "$(printf '%s' "$PAIRING" | tr -d '\n')"
