#!/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-bootstrap-apt <ENDPOINT> [auto] (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-bootstrap-apt ...

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_AUTO="${2}"
: ${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-bootstrap-apt-${MBD_IDENTITY}.list"
MBD_APT_KEY="/etc/apt/trusted.gpg.d/mini-buildd-bootstrap-apt-${MBD_IDENTITY}.asc"

cleanup()
{
	printf "\nCleanup:\n"
	rm --verbose "${MBD_APT_FILE}" "${MBD_APT_KEY}"
}
trap cleanup EXIT

ask()
{
	if [ "${MBD_AUTO}" != "auto" ]; then
		local dummy
		read -p"${1} (<RET> to continue, <Ctrl-C> to cancel)" dummy
	fi
}

# 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
}

[ -n "${MBD_CODENAME}" ] && [ "${MBD_CODENAME}" != "n/a" ] || { printf "E: Could not determine codename (${MBD_CODENAME}) -- please override (try --help for usage).\n" >&2; exit 2; }

ask "TOFU strap '${MBD_KEYRING_PACKAGE}' from '${MBD_ENDPOINT}' (ID=${MBD_IDENTITY}) for '${MBD_CODENAME}'"

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

printf "\nKey to trust                : %s"     "${MBD_APT_KEY}"
printf "\nAPT line for keyring package: %s\n\n" "${MBD_APT_FILE}"
ask "You may check generated temporary files now (will be automatically removed on exit)"

# 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 --quiet --quiet update
apt-get install "${MBD_KEYRING_PACKAGE}"

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