#!/bin/bash -e

DESCRIPTION="Automated TOFU-style archive keyring package installation from any mini-buildd endpoint."

case "${1}" in
	"")
		printf "E: No endpoint given (try --help for usage).\n" >&2
		exit 1
		;;
	"--help")
		cat <<EOF
Usage: mini-buildd-apt-bootstrap <ENDPOINT> (as user root)

${DESCRIPTION}

You may override automatic perusal of 'codename' (your system) and/or
'identity' (mini-buildd's identity) calling us like so:

MBD_CODENAME=foo MBD_IDENTITY=bar MBD_APT_LINE="deb ..." mini-buildd-apt-bootstrap ...

This may be useful if computation fails (tools not available) or is
wrong for some reason.

EOF
	exit 0
esac

[ $(id -u) -eq 0 ] || { printf "E: Needs to be run as root (try --help for usage).\n" >&2; exit 1; }

MBD_ENDPOINT="${1}"
: ${MBD_CODENAME:=$(lsb_release --codename --short)}
: ${MBD_IDENTITY:=$(mini-buildd-api status "${MBD_ENDPOINT}" | jq --raw-output ".identity")}
: ${MBD_APT_LINE:=$(mini-buildd-api sources_list "${MBD_ENDPOINT}" --codenames ${MBD_CODENAME} --suites stable)}

MBD_KEYRING_PACKAGE="${MBD_IDENTITY}-archive-keyring"

MBD_APT_FILE="/etc/apt/sources.list.d/mini-buildd-apt-bootstrap-${MBD_IDENTITY}.list"
MBD_APT_KEY="/etc/apt/trusted.gpg.d/mini-buildd-apt-bootstrap-${MBD_IDENTITY}.asc"

cleanup()
{
	rm --verbose --interactive "${MBD_APT_FILE}" "${MBD_APT_KEY}"
}
trap cleanup EXIT


# Get key from api tool if possible, but compat-fallback to pure HTTP in case we don't have it
get_pub_key()
{
	if command -v mini-buildd-api >/dev/null; then
		mini-buildd-api pub_key "${MBD_ENDPOINT}"
	else
		wget --quiet --output-document=- "${MBD_ENDPOINT}/mini_buildd/api/pub_key/" | jq --raw-output ".__plain__"
	fi
}

read -p"TOFU strap '${MBD_KEYRING_PACKAGE}' from '${MBD_ENDPOINT}' (ID=${MBD_IDENTITY}) for '${MBD_CODENAME}'? (Ctrl-C to cancel)" DUMMY

get_pub_key >"${MBD_APT_KEY}"
printf "%s\n" "${MBD_APT_LINE}" >"${MBD_APT_FILE}"

printf "\n"
printf "Key to trust                : %s\n" "${MBD_APT_KEY}"
printf "APT line for keyring package: %s\n" "${MBD_APT_FILE}"
read -p"Check files, then continue (Ctrl-C to cancel)" DUMMY

# Compat for jessie or older: Needs extra apt-key add call, which mini-buildd no longer supports with his keyring package.
case ${MBD_CODENAME} in
	jessie|wheezy|squeeze)
		apt-key add "${MBD_APT_KEY}"
		;;
esac

apt-get update
apt-get install "${MBD_KEYRING_PACKAGE}"

printf "\nOK: TOFU install of ${MBD_KEYRING_PACKAGE} from ${MBD_ENDPOINT} successful:\n\n"
dpkg -s weslok-archive-keyring
printf "\n"
