#!/bin/sh
# Explicit administrator action, never called from package builds or Jobfile.
set -eu
root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
die() { printf 'prepare-ci-host: %s\n' "$*" >&2; exit 1; }
mode=${1:---plan}
case "$mode" in
--plan | --simulate | --install) [ "$#" -eq 0 ] || shift ;;
*) die 'usage: prepare-ci-host.sh [--plan|--simulate|--install] [BOOTSTRAP_DIR]' ;;
esac
[ "$#" -le 1 ] || die 'expected at most one foundationpkgs-binaries directory'
bootstrap=${1:-$root/../foundationpkgs-binaries}
[ -d "$bootstrap" ] || die "foundationpkgs-binaries directory not found: $bootstrap"
bootstrap=$(CDPATH= cd -- "$bootstrap" && pwd)
if [ "$mode" != --plan ]; then
	[ -r /etc/os-release ] || die 'Debian 13 amd64 is required'
	(. /etc/os-release; [ "$ID" = debian ] && [ "$VERSION_ID" = 13 ]) || die 'Debian 13 is required'
	[ "$(dpkg --print-architecture)" = amd64 ] || die 'amd64 is required'
	[ "$mode" != --install ] || [ "$(id -u)" -eq 0 ] || die '--install requires root'
fi
work=$(mktemp -d "${TMPDIR:-/tmp}/fpkgs-host.XXXXXX")
trap 'rm -rf "$work"' EXIT
trap 'exit 1' HUP INT TERM
set --
count=0
while read -r kind item digest extra || [ -n "$kind" ]; do
	case "$kind" in '' | \#*) continue ;; esac
	[ -z "$extra" ] || die 'unexpected extra manifest fields'
	case "$kind" in
	apt)
		case "$item" in '' | [!a-z0-9]* | *[!a-z0-9+.-]*) die "invalid Debian package name: $item" ;; esac
		[ -z "$digest" ] || die "unexpected checksum for Debian package: $item"
		set -- "$@" "$item"
		printf 'apt %s\n' "$item"
		;;
	deb)
		case "$item" in
		/* | ../* | */../* | */.. | *[!a-zA-Z0-9_./+~:-]*) die "unsafe custom package path: $item" ;;
		esac
		case "$item" in packages/*.deb) ;; *) die "expected packages/.../*.deb: $item" ;; esac
		[ "${#digest}" -eq 64 ] || die "invalid SHA-256 for $item"
		case "$digest" in *[!0-9a-f]*) die "invalid SHA-256 for $item" ;; esac
		file=$work/$(basename "$item")
		[ ! -e "$file" ] || die "duplicate custom package filename: $item"
		cp "$bootstrap/$item" "$file"
		if command -v sha256sum >/dev/null 2>&1; then
			sum=$(sha256sum "$file")
		else
			sum=$(shasum -a 256 "$file")
		fi
		[ "${sum%% *}" = "$digest" ] || die "checksum mismatch: $item"
		chmod 0644 "$file"
		set -- "$@" "$file"
		printf 'deb %s %s\n' "$item" "$digest"
		;;
	*) die "unknown manifest entry: $kind" ;;
	esac
	count=$((count + 1))
done <"$root/.config/ci-packages.list"
[ "$count" -gt 0 ] || die 'empty package manifest'
[ "$mode" != --plan ] || exit 0
# APT's _apt user must be able to read these verified, non-secret staged files.
# The source checkout may be private; APT never needs access to it.
chmod 0755 "$work"
if [ "$mode" = --simulate ]; then
	export LC_ALL=C
	apt-get --simulate --no-remove --no-install-recommends install "$@"
else
	# Interactive APT confirmation; no unattended -y or implicit apt-get update.
	apt-get --no-remove --no-install-recommends install "$@"
fi
