#!/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 inspection (spec §6.1, decision P0-012, threat model M-04).
#
# Strictly read-only: this script never changes the host. The app streams it
# over the bootstrap SSH session and runs it as root:
#
#     sudo sh -s < inspect.sh
#
# It prints one JSON HostReport (contracts/bootstrap/host-report.schema.json)
# on stdout and nothing else. POSIX sh only; no bash, jq or python.

set -u
LC_ALL=C
export LC_ALL
SCRIPT_VERSION="1.1.0"
AGENT_PORT=47800

# ---------------------------------------------------------------- JSON helpers

# js VALUE: print VALUE as a JSON string.
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 "\"" }'
}

# jn VALUE: print VALUE as a JSON number, or null if it isn't one.
jn() {
	case "$1" in
	'' | *[!0-9]*) printf 'null' ;;
	*) printf '%s' "$1" ;;
	esac
}

# jb CONDITION-EXIT-STATUS: print true/false.
jb() { if [ "$1" -eq 0 ]; then printf 'true'; else printf 'false'; fi; }

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

FINDINGS=""
# finding SEVERITY CODE MESSAGE
finding() {
	f="{\"severity\":$(js "$1"),\"code\":$(js "$2"),\"message\":$(js "$3")}"
	if [ -z "$FINDINGS" ]; then FINDINGS="$f"; else FINDINGS="$FINDINGS,$f"; fi
}

# ---------------------------------------------------------------- facts

is_root=1
[ "$(id -u)" -eq 0 ] && is_root=0
[ "$is_root" -eq 0 ] || finding blocking not_root "Inspection must run as root (through sudo) to see Docker and system state."

# OS
ID="" ID_LIKE="" VERSION_ID="" PRETTY_NAME="" VERSION_CODENAME=""
if [ -r /etc/os-release ]; then
	# shellcheck disable=SC1091
	. /etc/os-release
fi
os_family=unknown
case "$ID" in
ubuntu | debian) os_family=debian ;;
rocky | almalinux) os_family=rhel ;;
esac
major=${VERSION_ID%%.*}
os_supported=1
case "$ID:$major" in
ubuntu:22 | ubuntu:24 | ubuntu:26 | debian:12 | debian:13 | rocky:9 | rocky:10 | almalinux:9 | almalinux:10) os_supported=0 ;;
esac
# Ubuntu interim (non-LTS) releases share a major with an LTS; only LTS counts.
if [ "$ID" = ubuntu ] && [ "$os_supported" -eq 0 ]; then
	case "$VERSION_ID" in 22.04 | 24.04 | 26.04) ;; *) os_supported=1 ;; esac
fi
if [ "$os_supported" -ne 0 ]; then
	finding blocking os_unsupported "${PRETTY_NAME:-This OS} isn't supported. ServerMage supports Ubuntu 22.04/24.04/26.04 LTS, Debian 12/13, Rocky Linux 9/10 and AlmaLinux 9/10."
fi

# Architecture
raw_arch=$(uname -m)
case "$raw_arch" in
x86_64 | amd64) arch=amd64 ;;
aarch64 | arm64) arch=arm64 ;;
*)
	arch=$raw_arch
	finding blocking arch_unsupported "CPU architecture $raw_arch isn't supported. ServerMage needs a 64-bit x86 or ARM server."
	;;
esac

hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null || hostname)
kernel=$(uname -r)

cpu_model=$(awk -F: '/^(model name|Model|Hardware)/ { sub(/^[ \t]+/, "", $2); print $2; exit }' /proc/cpuinfo 2>/dev/null)
if [ -z "$cpu_model" ] && [ -r /sys/firmware/devicetree/base/model ]; then
	cpu_model=$(tr -d '\000' </sys/firmware/devicetree/base/model)
fi
# ARM CPUs often have no model name in /proc/cpuinfo; lscpu decodes the part ID.
if [ -z "$cpu_model" ] && have lscpu; then
	cpu_model=$(lscpu 2>/dev/null | awk -F: '/^Model name:/ { sub(/^[ \t]+/, "", $2); print $2; exit }')
	# lscpu prints "-" for parts it doesn't know; fall back to the vendor.
	if [ -z "$cpu_model" ] || [ "$cpu_model" = - ]; then
		vendor=$(lscpu 2>/dev/null | awk -F: '/^Vendor ID:/ { sub(/^[ \t]+/, "", $2); print $2; exit }')
		cpu_model=${vendor:+$vendor processor}
	fi
fi
cpu_cores=$(grep -c '^processor' /proc/cpuinfo 2>/dev/null)

mem_total=$(awk '/^MemTotal:/ { print $2 * 1024 }' /proc/meminfo)
mem_avail=$(awk '/^MemAvailable:/ { print $2 * 1024 }' /proc/meminfo)
if [ -n "$mem_total" ] && [ "$mem_total" -lt 1073741824 ]; then
	finding warning low_memory "The server has less than 1 GB of memory. Most services need more."
fi

# Disks: the filesystems that will hold the Agent, Docker data and images.
disk_json=""
for p in / /opt /var/lib/docker; do
	d=$p
	while [ ! -e "$d" ]; do d=$(dirname "$d"); done
	# POSIX df -P: 1024-byte blocks; columns: fs total used avail cap mount.
	# Word splitting into $1..$3 is intended.
	# shellcheck disable=SC2046
	set -- $(df -P -k "$d" 2>/dev/null | awk 'NR == 2 { print $2, $4, $6 }')
	[ $# -eq 3 ] || continue
	entry="{\"path\":$(js "$p"),\"mountpoint\":$(js "$3"),\"total_bytes\":$(jn $(($1 * 1024))),\"available_bytes\":$(jn $(($2 * 1024)))}"
	if [ -z "$disk_json" ]; then disk_json="$entry"; else disk_json="$disk_json,$entry"; fi
	if [ "$p" = /var/lib/docker ] && [ "$2" -lt 5242880 ]; then
		finding warning low_disk "Less than 5 GB is free where Docker stores images ($3). Installing services may fail."
	fi
done

systemd=1
[ -d /run/systemd/system ] && systemd=0
[ "$systemd" -eq 0 ] || finding blocking no_systemd "ServerMage needs a systemd-based OS to manage the Docker service."

# SELinux
if [ -r /sys/fs/selinux/enforce ]; then
	if [ "$(cat /sys/fs/selinux/enforce)" = 1 ]; then selinux=enforcing; else selinux=permissive; fi
elif [ -r /etc/selinux/config ] && grep -q '^SELINUX=disabled' /etc/selinux/config; then
	selinux=disabled
else
	selinux=absent
fi

# Firewalls
ufw=absent
if have ufw; then
	ufw=inactive
	if grep -qi '^ENABLED=yes' /etc/ufw/ufw.conf 2>/dev/null; then ufw=active; fi
fi
firewalld=absent
if have firewall-cmd; then
	firewalld=not_running
	if have systemctl && systemctl is-active --quiet firewalld 2>/dev/null; then firewalld=running; fi
fi
if [ "$ufw" = active ] || [ "$firewalld" = running ]; then
	finding info firewall_active "A firewall is active. Setup will allow the ServerMage Agent port ($AGENT_PORT/tcp) and Bonjour (5353/udp)."
fi

# Docker
docker_installed=1 docker_running=1 docker_source=none
docker_client="" docker_server="" docker_api=""
if have docker; then
	docker_installed=0
	docker_client=$(docker version --format '{{.Client.Version}}' 2>/dev/null)
	if docker --version 2>/dev/null | grep -qi podman; then
		docker_source=podman-docker
	elif have dpkg-query && dpkg-query -W -f='${Status}' docker-ce 2>/dev/null | grep -q 'install ok installed'; then
		docker_source=docker-ce
	elif have dpkg-query && dpkg-query -W -f='${Status}' docker.io 2>/dev/null | grep -q 'install ok installed'; then
		docker_source=docker.io
	elif have rpm && rpm -q docker-ce >/dev/null 2>&1; then
		docker_source=docker-ce
	else
		docker_source=other
	fi
	if docker_server=$(docker version --format '{{.Server.Version}}' 2>/dev/null) && [ -n "$docker_server" ]; then
		docker_running=0
		docker_api=$(docker version --format '{{.Server.APIVersion}}' 2>/dev/null)
	fi
fi
if [ "$docker_source" = podman-docker ]; then
	finding blocking podman_docker "The docker command on this server is Podman. ServerMage 1.0 needs Docker Engine."
elif [ "$docker_installed" -ne 0 ]; then
	finding info docker_missing "Docker isn't installed. Setup will install Docker Engine from Docker's official repository."
elif [ "$docker_running" -ne 0 ]; then
	# Why it isn't running, when the journal says (it needs root; setup
	# runs this with sudo).
	docker_log=""
	have journalctl && docker_log=$(journalctl -u docker.service --no-pager -n 80 2>/dev/null)
	kmod_pkg="kernel-modules-extra-$(uname -r)"
	if [ "$os_family" = rhel ] && printf '%s' "$docker_log" | grep -qiE 'missing kernel module|extension addrtype|modprobe|failed to add jump rules|RULE_APPEND failed|failed to register "bridge" driver' &&
		have rpm && ! rpm -q "$kmod_pkg" >/dev/null 2>&1; then
		finding warning docker_kernel_modules "Docker can't start: the network modules it needs aren't installed for the running kernel ($(uname -r)). This can happen after a kernel update. Setup will install $kmod_pkg and start Docker."
	elif have systemctl && systemctl show -p Result docker.service 2>/dev/null | grep -q start-limit; then
		finding warning docker_start_limit "Docker failed to start several times, so the system stopped retrying. Setup will try again."
	else
		finding warning docker_not_running "Docker is installed but not running. Setup will start it."
	fi
else
	dmajor=${docker_server%%.*}
	dminor=${docker_server#*.}
	dminor=${dminor%%.*}
	case "$dmajor$dminor" in *[!0-9]*) dmajor=0 dminor=0 ;; esac
	if [ "$dmajor" -lt 20 ] || { [ "$dmajor" -eq 20 ] && [ "$dminor" -lt 10 ]; }; then
		finding blocking docker_too_old "Docker $docker_server is too old. ServerMage needs Docker 20.10 or newer."
	fi
fi

# RHEL-family packages that Docker's containerd.io replaces. Setup checks
# the exact transaction with dnf before changing anything.
conflicts=""
if [ "$os_family" = rhel ] && have rpm && [ "$docker_installed" -ne 0 ]; then
	for pkg in runc containerd; do
		if rpm -q "$pkg" >/dev/null 2>&1; then conflicts="$conflicts $pkg"; fi
	done
fi
conflicts_json=""
for pkg in $conflicts; do
	if [ -z "$conflicts_json" ]; then conflicts_json=$(js "$pkg"); else conflicts_json="$conflicts_json,$(js "$pkg")"; fi
done
if [ -n "$conflicts" ]; then
	finding warning conflicting_packages "Installing Docker may replace these packages:$conflicts. Setup will ask before removing anything."
fi
if [ "$os_family" = rhel ] && have rpm && rpm -q podman >/dev/null 2>&1; then
	finding info podman_present "Podman is installed. It can keep running alongside Docker; ServerMage manages only Docker."
fi

# Existing ServerMage installation
sm_dir=1
[ -d /opt/servermage ] && sm_dir=0
agent_state=absent agent_image="" agent_version=""
if [ "$docker_running" -eq 0 ]; then
	if s=$(docker inspect --format '{{.State.Status}}' servermage-agent 2>/dev/null); then
		agent_state=$s
		agent_image=$(docker inspect --format '{{.Config.Image}}' servermage-agent 2>/dev/null)
		agent_version=$(docker exec servermage-agent /servermage-agent version 2>/dev/null)
	fi
fi
if [ "$docker_running" -eq 0 ] && [ "$agent_state" = absent ] &&
	docker inspect servermage-agent-previous >/dev/null 2>&1; then
	agent_state=exited
	finding warning agent_update_interrupted "A ServerMage update was interrupted, so ServerMage isn't running. Setup will bring back the version that was installed."
elif [ "$agent_state" != absent ] && [ "$agent_state" != running ]; then
	finding warning agent_stopped "ServerMage is installed but not running ($agent_state). Setup will start it, keeping its data, and issue a new pairing code."
elif [ "$agent_state" != absent ]; then
	finding info agent_present "A ServerMage Agent is already installed. Setup will keep its data and issue a new pairing code."
fi

# Agent port: free unless something other than our Agent listens on it.
port_state=free
if have ss && ss -Hltn "sport = :$AGENT_PORT" 2>/dev/null | grep -q .; then
	port_state=in_use
	if [ "$agent_state" = running ]; then port_state=agent; fi
fi
if [ "$port_state" = in_use ]; then
	finding blocking port_in_use "Port $AGENT_PORT is used by another program. The ServerMage Agent needs it."
fi

# Docker's package repository, needed only if Docker must be installed.
repo_reachable=1
if have curl; then
	curl -fsS -o /dev/null --max-time 10 https://download.docker.com/linux/ && repo_reachable=0
elif have wget; then
	wget -q -O /dev/null -T 10 https://download.docker.com/linux/ && repo_reachable=0
fi
if [ "$docker_installed" -ne 0 ] && [ "$repo_reachable" -ne 0 ]; then
	finding blocking repo_unreachable "The server can't reach download.docker.com, so Docker can't be installed. Check its internet connection."
fi

# Existing containers (shown as external, D-015). Docker's json template
# function does the escaping.
containers=""
if [ "$docker_running" -eq 0 ]; then
	containers=$(docker ps -a --format '{"id":{{json .ID}},"name":{{json .Names}},"image":{{json .Image}},"state":{{json .State}},"status":{{json .Status}}}' 2>/dev/null | awk 'NR > 1 { printf "," } { printf "%s", $0 }')
fi

# ---------------------------------------------------------------- report

printf '{'
printf '"report_version":1,'
printf '"script_version":%s,' "$(js "$SCRIPT_VERSION")"
printf '"collected_at":%s,' "$(js "$(date -u +%Y-%m-%dT%H:%M:%SZ)")"
printf '"user":{"is_root":%s,"sudo_user":%s},' "$(jb "$is_root")" "$(js "${SUDO_USER:-}")"
printf '"hostname":%s,' "$(js "$hostname")"
printf '"os":{"id":%s,"id_like":%s,"version_id":%s,"codename":%s,"pretty_name":%s,"family":%s,"kernel":%s,"supported":%s},' \
	"$(js "$ID")" "$(js "$ID_LIKE")" "$(js "$VERSION_ID")" "$(js "$VERSION_CODENAME")" "$(js "$PRETTY_NAME")" \
	"$(js "$os_family")" "$(js "$kernel")" "$(jb "$os_supported")"
printf '"architecture":%s,' "$(js "$arch")"
printf '"cpu":{"model":%s,"cores":%s},' "$(js "$cpu_model")" "$(jn "$cpu_cores")"
printf '"memory":{"total_bytes":%s,"available_bytes":%s},' "$(jn "$mem_total")" "$(jn "$mem_avail")"
printf '"disks":[%s],' "$disk_json"
printf '"systemd":%s,' "$(jb "$systemd")"
printf '"selinux":%s,' "$(js "$selinux")"
printf '"firewall":{"ufw":%s,"firewalld":%s},' "$(js "$ufw")" "$(js "$firewalld")"
printf '"docker":{"installed":%s,"running":%s,"source":%s,"client_version":%s,"server_version":%s,"api_version":%s},' \
	"$(jb "$docker_installed")" "$(jb "$docker_running")" "$(js "$docker_source")" \
	"$(js "$docker_client")" "$(js "$docker_server")" "$(js "$docker_api")"
printf '"conflicting_packages":[%s],' "$conflicts_json"
printf '"servermage":{"dir_exists":%s,"agent_container":%s,"agent_image":%s,"agent_version":%s},' \
	"$(jb "$sm_dir")" "$(js "$agent_state")" "$(js "$agent_image")" "$(js "$agent_version")"
printf '"agent_port":{"port":%s,"state":%s},' "$AGENT_PORT" "$(js "$port_state")"
printf '"docker_repo_reachable":%s,' "$(jb "$repo_reachable")"
printf '"containers":[%s],' "$containers"
printf '"findings":[%s]' "$FINDINGS"
printf '}\n'
