#!/bin/sh
# glocker bootstrap installer:
#   curl -fsSL https://glockerapp.com/glocker-installer.sh | sh
# Fetches the latest signed release tarball, verifies it, and runs the installer
# (install.sh) inside it. It writes nothing to the system itself — the install,
# which asks for sudo, happens entirely inside the verified tarball.
set -eu

REPO="glocker-app/glocker"
MINISIGN_PUBKEY="RWT2ioF8xC/sE5SAAyubQQGPAJWWZxougVjndvUzoRH1D1/C8mOoFK5i"

fail() { echo "error: $*" >&2; exit 1; }

# Fetch with a connect/transfer timeout and retries so a stalled connection
# fails fast and retries instead of hanging forever with no output.
#   dl URL OUTFILE [--bar]
dl() {
	_u=$1; _o=$2
	if [ "${3:-}" = "--bar" ]; then
		curl -fL --progress-bar --connect-timeout 20 --max-time 900 \
			--retry 3 --retry-delay 2 -o "$_o" "$_u"
	else
		curl -fsSL --connect-timeout 20 --max-time 120 \
			--retry 3 --retry-delay 2 -o "$_o" "$_u"
	fi
}

[ "$(uname -s)" = "Linux" ] || fail "glocker is Linux-only"
case "$(uname -m)" in
	x86_64|amd64) ;;
	*) fail "only linux/amd64 is published as a binary — build from source: https://github.com/$REPO" ;;
esac
for t in curl tar sha256sum; do
	command -v "$t" >/dev/null 2>&1 || fail "$t is required"
done

echo "Resolving the latest glocker release…"
tag=$(curl -fsSL --connect-timeout 20 --max-time 60 --retry 3 --retry-delay 2 \
	"https://api.github.com/repos/$REPO/releases/latest" \
	| sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
[ -n "$tag" ] || fail "couldn't determine the latest release tag"

name="glocker-$tag-linux-amd64"
base="https://github.com/$REPO/releases/download/$tag"

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cd "$tmp"

echo "Downloading $name.tar.gz ($tag)…"
dl "$base/$name.tar.gz" "$name.tar.gz" --bar || fail "download failed"
echo "Verifying…"
dl "$base/SHA256SUMS"         SHA256SUMS         || fail "couldn't fetch SHA256SUMS"
dl "$base/SHA256SUMS.minisig" SHA256SUMS.minisig || true

# Signature check (strongest) when minisign is installed; always check the hash.
if command -v minisign >/dev/null 2>&1 && [ -s SHA256SUMS.minisig ]; then
	minisign -Vm SHA256SUMS -P "$MINISIGN_PUBKEY" >/dev/null \
		|| fail "minisign signature check failed — aborting"
	echo "✓ minisign signature verified"
else
	echo "! minisign not installed — skipping signature check (the hash is still verified)."
	echo "  For the full signed check, see https://glockerapp.com/"
fi

grep " $name.tar.gz\$" SHA256SUMS | sha256sum -c - >/dev/null \
	|| fail "checksum mismatch — aborting"
echo "✓ sha256 verified"

tar -xzf "$name.tar.gz"
echo
sh "$name/install.sh"
