#! /bin/sh

set -e


which cubbli-conf >/dev/null 2>&1 || exit 0


is_installed() {
	dpkg -l "cubbli-misc-$1" 2>&1 | tail -1 | grep -q '^ii'
}

has_package() {
	apt-cache show "cubbli-misc-$1" >/dev/null 2>&1
}

try_install() {
	export DEBIAN_FRONTEND=noninteractive
	export DEBIAN_PRIORITY=critical
	aptitude install -y "cubbli-misc-$1"
}

try_package() {
	pkg="$1"

	if is_installed "$pkg"; then
		exit 0
	fi

	has_package "$pkg" || return 0

	if try_install "$pkg"; then
		exit 0
	else
		echo "Unable to install cubbli-misc-$pkg" >&2
		exit 1
	fi
}


# Older generation cubbli-conf prints "Default profile: $profile",
# future versions may print just "$profile". In any case the profile
# always comes last.

profile=$(cubbli-conf profile | sed 's/.* //')
pri=$(echo "$profile" | cut -d / -f 1)
sec=$(echo "$profile" | cut -d / -f 2)


# "check" returns 1 if the script should be run
if test "x$1" = "xcheck"; then
	is_installed $pri-$sec && exit 0 || true
	has_package $pri-$sec && exit 1 || true
	is_installed $pri && exit 0 || true
	has_package $pri && exit 1 || true
	exit 0
fi


# try_package will exit if package is already installed
try_package $pri-$sec
try_package $pri
