#!/usr/bin/env bash
# Sends the live runtime artifacts to the hosts listed in DISTRIBUTE_TARGETS.
# Each target runs capy-bearer-receive as the forced command of DISTRIBUTE_KEY.
set -uo pipefail

CONFIG=/etc/default/capy-bearer-update
# shellcheck disable=SC1090
[[ -r $CONFIG ]] && . "$CONFIG"

LIVE=${LIVE:-/opt/capy-bearer}
DISTRIBUTE_TARGETS=${DISTRIBUTE_TARGETS:-}
DISTRIBUTE_KEY=${DISTRIBUTE_KEY:-/root/.ssh/capy_bearer_distribute_ed25519}
revision=${1:-$(git -C "$LIVE" rev-parse HEAD)}

status=0
for target in $DISTRIBUTE_TARGETS; do
	if tar -C "$LIVE" -c bin/bearer_fastcgi.linux.bin bin/capyc bin/wasm/core.wasm |
		ssh -i "$DISTRIBUTE_KEY" -o BatchMode=yes -o ConnectTimeout=15 "$target" "capy-bearer-receive $revision"; then
		echo "distributed $revision to $target"
	else
		echo "distribution to $target failed" >&2
		status=1
	fi
done
exit $status
