#!/bin/sh
# add-repo.sh [URL]: run ON THE TABLET. Adds this package repository to an
# existing Vellum install: fetches the signing key, checks its fingerprint,
# appends the repository line and refreshes the index. Safe to run twice.
#
# Usage on the device (Vellum must already be installed):
#   wget -q -O - https://rm.thefrys.net/add-repo.sh | sh
# A different URL (a LAN mirror, say) can be passed as the first argument.
set -eu

URL=${1:-${REPO_URL:-https://rm.thefrys.net}}
[ -n "$URL" ] || { echo "usage: add-repo.sh URL" >&2; exit 2; }
URL=${URL%/}

KEY=fry-rm2.rsa.pub
# SHA-256 of keys/fry-rm2.rsa.pub. Bump this if the key is ever rotated.
SHA=6a3872a0659449e21916efc2742a21c7ac435572f2909d528eb4419cf21a9845

V=/home/root/.vellum/etc/apk
[ -d "$V/keys" ] || {
	echo "Vellum is not installed; see https://github.com/vellum-dev/vellum-cli" >&2
	exit 1
}

wget -q "$URL/keys/$KEY" -O "$V/keys/$KEY.new"
if ! echo "$SHA  $V/keys/$KEY.new" | sha256sum -c - >/dev/null; then
	rm -f "$V/keys/$KEY.new"
	echo "key fingerprint mismatch; not installing" >&2
	exit 1
fi
mv "$V/keys/$KEY.new" "$V/keys/$KEY"

# The repositories file may lack a final newline (vellum testing rewrites
# it that way), so always start our line on a fresh one.
if ! grep -qxF "$URL" "$V/repositories"; then
	printf '\n%s\n' "$URL" >> "$V/repositories"
fi

PATH=/home/root/.vellum/bin:$PATH vellum update
echo "repository added: $URL"
