#!/bin/sh
# CI data handoff only; signing runs under the separately provisioned publisher.
set -eu
[ "$#" -ge 2 ] || { echo 'usage: apt-delivery.sh transfer|deploy REV [PACKAGE...]' >&2; exit 1; }
action=$1
rev=$2
shift 2
case "$rev" in '' | *[!0-9a-f]*) exit 1 ;; esac
[ "${#rev}" -eq 40 ] || exit 1
self=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
receiver=${FPKGS_APT_RECEIVER:-/usr/local/libexec/foundationpkgs-apt}
case "$action" in
transfer)
	[ "$#" -gt 0 ] || { echo 'No Debian packages selected' >&2; exit 1; }
	handoff=${FPKGS_APT_HANDOFF:-/var/lib/foundationpkgs-handoff}
	work=$(mktemp -d "$handoff/.transfer.XXXXXX")
	trap 'rm -rf "$work"' 0
	trap 'exit 1' HUP INT TERM
	for pkg do
		case "$pkg" in '' | . | .. | *[!a-z0-9+.-]*) exit 1 ;; esac
		status=$(FPKGS_FORMAT=deb "$self/fpkgs-ci.sh" status "$pkg" x86_64-unknown-linux-gnu "$rev")
		archive=$(printf '%s\n' "$status" | awk -F= '$1 == "artifact_path" {print substr($0,15)}')
		[ -f "$archive" ] || exit 1
		mkdir "$work/$pkg"
		cp "${archive%/*}/manifest" "${archive%/*}/SHA256SUMS" "${archive%/*}/build.log" "$archive" "$work/$pkg/"
	done
	git -C "${FPKGS_ROOT:-.}" archive --format=tar.gz "$rev" > "$work/source.tar.gz"
	# The receiver may read the bundle, but never executes or extracts its source.
	chmod -R a+rX "$work"
	sudo -n -u fpkgs-publisher "$receiver" receive "$rev" "$work"
	;;
deploy)
	[ "$#" -eq 0 ] || exit 1
	sudo -n -u fpkgs-publisher "$receiver" deploy "$rev"
	;;
*) exit 1 ;;
esac
