#!/bin/sh
# Native Debian publisher. Install root-owned; run as the separate publisher user.
set -eu
umask 022
root=${FPKGS_APT_ROOT:-$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)}
public=${FPKGS_APT_PUBLIC_ROOT:-/srv/http/dl.nply.org/foundationpkgs-binaries}
url=${FPKGS_APT_URL:-https://nply.org/dl/foundationpkgs-binaries/apt}
fingerprint=${FPKGS_APT_FINGERPRINT:-9EF366A63EC38FB0A160549D33F4C03101AEC8D2}
export LC_ALL=C
fail() { printf 'publish-apt: %s\n' "$*" >&2; exit 1; }
field() { awk -F= -v key="$2" '$1 == key { n++; value=substr($0,length(key)+2) } END { if (n != 1) exit 1; print value }' "$1"; }
registry() { (cd "$1" && find . -type f ! -name RECEIPT.sha256 -print | sort | while IFS= read -r file; do sha256sum "$file"; done); }
verify_bundle() {
	bundle=$1
	[ -f "$bundle/source.tar.gz" ] || fail 'Missing source snapshot'
	[ -z "$(find "$bundle" ! -type f ! -type d -print)" ] || fail 'Non-regular bundle entry'
	count=0
	for dir in "$bundle"/*; do
		[ -d "$dir" ] || continue
		pkg=${dir##*/}
		case "$pkg" in '' | . | .. | *[!a-z0-9+.-]*) fail 'Invalid package name' ;; esac
		manifest=$dir/manifest
		[ "$(field "$manifest" gitrev)" = "$rev" ] || fail 'Wrong revision'
		[ "$(field "$manifest" pkgname)" = "$pkg" ] || fail 'Wrong package'
		[ "$(field "$manifest" target)" = x86_64-unknown-linux-gnu ] || fail 'Wrong target'
		[ "$(field "$manifest" format)" = deb ] || fail 'Not a Debian publication'
		file=$(field "$manifest" artifact)
		case "$file" in "$pkg"_*.deb) ;; *) fail 'Unexpected artifact name' ;; esac
		case "$file" in *[!a-zA-Z0-9_.+~:-]*) fail 'Unsafe artifact path' ;; esac
		# This backend produces one primary .deb; do not accept arbitrary checksum paths.
		awk -v file="$file" 'NF != 2 || length($1) != 64 || $1 ~ /[^0-9a-f]/ || ($2 != file && $2 != "./" file) { exit 1 } END { if (NR != 1) exit 1 }' "$dir/SHA256SUMS" || fail 'Invalid checksum registry'
		(cd "$dir" && sha256sum -c SHA256SUMS) || fail 'Artifact checksum mismatch'
		[ -f "$dir/build.log" ] || fail 'Missing build log'
		[ "$(dpkg-deb -f "$dir/$file" Package)" = "$pkg" ] || fail 'Control package mismatch'
		version=$(dpkg-deb -f "$dir/$file" Version)
		arch=$(dpkg-deb -f "$dir/$file" Architecture)
		case "$arch" in amd64 | all) ;; *) fail 'Unsupported architecture' ;; esac
		[ "$file" = "${pkg}_${version}_${arch}.deb" ] || fail 'Control version/architecture mismatch'
		count=$((count + 1))
	done
	[ "$count" -gt 0 ] || fail 'Empty release'
}
case "$fingerprint" in *[!0-9A-F]*) fail 'Invalid fingerprint' ;; esac
[ "${#fingerprint}" -eq 40 ] || fail 'Expected full signing fingerprint'
[ "$#" -ge 2 ] || fail 'usage: publish-apt.sh receive REV BUNDLE | deploy REV'
action=$1
rev=$2
case "$rev" in '' | *[!0-9a-f]*) fail 'Expected full commit SHA' ;; esac
[ "${#rev}" -eq 40 ] || fail 'Expected full commit SHA'
mkdir -p "$root/provenance" "$root/archive/pool/main" "$root/repository-releases"
mkdir "$root/.apt-publish-lock" || fail 'Another publisher is active; inspect lock before removing'
temporary=
cleanup() { [ -z "$temporary" ] || rm -rf "$temporary"; rmdir "$root/.apt-publish-lock"; }
trap cleanup 0
trap 'exit 1' HUP INT TERM
receipt=$root/provenance/$rev
case "$action" in
receive)
	[ "$#" -eq 3 ] || fail 'Expected a bundle directory'
	[ -d "$3" ] && [ ! -L "$3" ] || fail 'Invalid bundle directory'
	[ -z "$(find "$3" ! -type f ! -type d -print)" ] || fail 'Non-regular incoming entry'
	temporary=$(mktemp -d "$root/provenance/.incoming.XXXXXX")
	rsync -rt -- "$3/" "$temporary/"
	verify_bundle "$temporary"
	registry "$temporary" > "$temporary/RECEIPT.sha256"
	if [ -e "$receipt" ]; then
		(cd "$receipt" && sha256sum -c RECEIPT.sha256)
		cmp "$temporary/RECEIPT.sha256" "$receipt/RECEIPT.sha256" || fail 'Revision already retained with different bytes'
	else
		mv "$temporary" "$receipt"
		temporary=
	fi
	printf 'Retained verified CI release: %s\n' "$rev"
	;;
deploy)
	[ "$#" -eq 2 ] || fail 'Unexpected deploy arguments'
	[ -d "$receipt" ] || fail 'Transfer this revision first'
	(cd "$receipt" && sha256sum -c RECEIPT.sha256)
	verify_bundle "$receipt"
	# Preflight every collision before changing the retained pool.
	for dir in "$receipt"/*; do
		[ -d "$dir" ] || continue
		pkg=${dir##*/}
		file=$(field "$dir/manifest" artifact)
		first=$(printf '%.1s' "$pkg")
		archive=$root/archive/pool/main/$first/$pkg
		if [ -e "$archive/$file" ]; then
			cmp "$dir/$file" "$archive/$file" || fail "Immutable version differs: $file; increment pkgrel"
		fi
	done
	for dir in "$receipt"/*; do
		[ -d "$dir" ] || continue
		pkg=${dir##*/}
		file=$(field "$dir/manifest" artifact)
		first=$(printf '%.1s' "$pkg")
		archive=$root/archive/pool/main/$first/$pkg
		mkdir -p "$archive"
		[ -e "$archive/$file" ] || install -m644 "$dir/$file" "$archive/$file"
	done
	identifier=$(date -u +%Y%m%dT%H%M%SZ)-$(printf '%.12s' "$rev")-$$
	stage=$root/repository-releases/$identifier
	mkdir "$stage"
	# Retain signed snapshots before changing the served symlink. Never prune releases.
	cp -al "$root/archive/pool" "$stage/pool"
	index=$stage/dists/trixie/main/binary-amd64
	mkdir -p "$index"
	(cd "$stage" && apt-ftparchive packages pool) > "$index/Packages"
	[ -s "$index/Packages" ] || fail 'Empty package index'
	[ "$(grep -c '^Filename: ' "$index/Packages")" -eq "$(find "$stage/pool" -type f -name '*.deb' | wc -l)" ] || fail 'Incomplete package index'
	gzip -n -c "$index/Packages" > "$index/Packages.gz"
	previous=$root/repository/dists/trixie/main/binary-amd64/by-hash
	[ ! -d "$previous" ] || cp -a "$previous" "$index/by-hash"
	for file in Packages Packages.gz; do
		for algorithm in SHA256 SHA512; do
			case "$algorithm" in SHA256) sum=$(sha256sum "$index/$file") ;; SHA512) sum=$(sha512sum "$index/$file") ;; esac
			mkdir -p "$index/by-hash/$algorithm"
			cp "$index/$file" "$index/by-hash/$algorithm/${sum%% *}"
		done
	done
	(cd "$stage" && apt-ftparchive \
		-o APT::FTPArchive::Release::Origin='Foundation Packages' \
		-o APT::FTPArchive::Release::Label='Foundation Packages Binaries' \
		-o APT::FTPArchive::Release::Suite=trixie \
		-o APT::FTPArchive::Release::Codename=trixie \
		-o APT::FTPArchive::Release::Architectures=amd64 \
		-o APT::FTPArchive::Release::Components=main \
		-o APT::FTPArchive::Release::ValidTime=7776000 \
		-o APT::FTPArchive::Release::Acquire-By-Hash=yes \
		release dists/trixie) > "$stage/dists/trixie/Release"
	for mode in clearsign detach-sign; do
		case "$mode" in clearsign) output=InRelease ;; detach-sign) output=Release.gpg ;; esac
		gpg --batch --yes --local-user "$fingerprint" --digest-algo SHA256 --armor \
			--output "$stage/dists/trixie/$output" --"$mode" "$stage/dists/trixie/Release"
	done
	gpg --batch --export "$fingerprint" > "$stage/foundationpkgs-archive-keyring.gpg"
	gpgv --keyring "$stage/foundationpkgs-archive-keyring.gpg" "$stage/dists/trixie/Release.gpg" "$stage/dists/trixie/Release"
	(cd "$stage" && find . -type f ! -name SHA256SUMS -print | sort | while IFS= read -r file; do sha256sum "$file"; done) > "$stage/SHA256SUMS"
	mkdir -p "$public/.staging/$identifier" "$public/releases"
	rsync -rt --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r "$stage/" "$public/.staging/$identifier/"
	(cd "$public/.staging/$identifier" && sha256sum -c SHA256SUMS)
	mv "$public/.staging/$identifier" "$public/releases/$identifier"
	ln -s "repository-releases/$identifier" "$root/.repository-next"
	mv -Tf "$root/.repository-next" "$root/repository"
	ln -s "releases/$identifier" "$public/.apt-next"
	mv -Tf "$public/.apt-next" "$public/apt"
	# Activation is not success until the actual HTTPS endpoint matches every file.
	temporary=$(mktemp -d "$root/.https-check.XXXXXX")
	while read -r expected file; do
		curl -fsSL --max-time 60 "$url/${file#./}" -o "$temporary/file"
		actual=$(sha256sum "$temporary/file")
		[ "${actual%% *}" = "$expected" ] || fail "HTTPS checksum mismatch: $file"
	done < "$stage/SHA256SUMS"
	curl -fsSL --max-time 60 "$url/SHA256SUMS" -o "$temporary/sums"
	cmp "$temporary/sums" "$stage/SHA256SUMS"
	printf '%s\n' "$identifier" > "$receipt/DEPLOYED"
	printf 'Published and verified retained + HTTPS release: %s (%s)\n' "$identifier" "$rev"
	;;
*) fail 'Unknown action' ;;
esac
