#!/bin/sh
# 123infra installer - beta channel.
#
# STUB. Fetches a participant's own release candidate and shows what it
# would install. It runs nothing and writes nothing outside a temp dir.
#
# The beta archive is never a public download: every copy is watermarked to
# one participant and served from a signed, expiring URL that their portal
# session produced. So this script takes that URL rather than a version.
#
#   curl -fsSL https://get-beta.123infra.io | sh -s -- --url '<your URL>'
set -eu

URL="${BETA_DOWNLOAD_URL:-}"
while [ $# -gt 0 ]; do
	case "$1" in
	--url)
		URL="${2:-}"
		shift 2
		;;
	--url=*)
		URL="${1#--url=}"
		shift
		;;
	-h | --help)
		sed -n '2,12p' "$0" 2>/dev/null || true
		exit 0
		;;
	*)
		echo "unknown argument: $1" >&2
		exit 2
		;;
	esac
done

if [ -z "$URL" ]; then
	echo "error: no download URL." >&2
	echo "Open the last page of your beta portal and copy the download link, then:" >&2
	echo "  curl -fsSL https://get-beta.123infra.io | sh -s -- --url '<your URL>'" >&2
	exit 2
fi

command -v curl >/dev/null || { echo "error: curl is required" >&2; exit 1; }
command -v unzip >/dev/null || { echo "error: unzip is required" >&2; exit 1; }

tmp="$(mktemp -d)"
# shellcheck disable=SC2064 # $tmp must expand now, not when the trap fires
trap "rm -rf '$tmp'" EXIT INT TERM

echo "-> fetching your release candidate"
if ! curl -fsSL "$URL" -o "$tmp/rc.zip"; then
	echo "error: that link did not work. Signed links expire - open the portal again." >&2
	exit 1
fi

echo "-> archive: $(wc -c <"$tmp/rc.zip" | tr -d ' ') bytes, sha256 $(sha256sum "$tmp/rc.zip" | cut -c1-16)..."

# Every copy carries this entry, naming who it was issued to. It is the
# reason a leaked archive can be traced back to one participant.
if ! unzip -p "$tmp/rc.zip" BETA-RECIPIENT >"$tmp/recipient" 2>/dev/null; then
	echo "error: no BETA-RECIPIENT entry - this is not a beta archive issued to you." >&2
	exit 1
fi
echo "-> issued to:"
sed 's/^/     /' "$tmp/recipient"

echo "-> contents:"
unzip -Z1 "$tmp/rc.zip" | head -20 | sed 's/^/     /'

echo
echo "STUB: stopping here. The real installer would now run installer/install.sh"
echo "from this archive. Nothing was installed and nothing was left on disk."
