#!/bin/bash
#This script is called by the launcher to check for updates to all OS museum
#packages (by installing a top-level meta-package that is set in the launcher
#config) and update any packages with new versions available. It will wait for
#any running guest VMs to shut down before checking, and set the mirror in
#/etc/apt/sources.list.d/os-museum.list from the launcher configuration file
#before updating.


. "`dirname $0`/bootscriptfunctions.sh"

if ! is_os_museum_vm
then
	exit 2
fi

if [ "$1" != "-c" ]
then
	run_terminal_if_needed "$0" "$@"
	if [ "$UID" = 0 ]
	then
		echo "Waiting for any running guest machines to shut down; if any are still running, please shut then down to allow updates to run"
		acquire_update_lock -x
		echo "All guests are shut down"
	fi
fi

if [ "$UID" != 0 ]
then
	exec sudo "$0" "$@"
fi

META_PACKAGE="`get_conf_value update meta_package`"

if [ ! "$META_PACKAGE" ]
then
	panic "META_PACKAGE unset (get_conf_value failed?)"
fi

if release_prep_enabled
then
	mirror="file:///media/host_apt"
else
	mirror="`get_conf_value update mirror`"
fi

if [ x"$mirror" = x ]
then
	panic "mirror unset in launcher.conf"
fi

suite="`get_conf_value update suite`"
if [ x"$suite" = x ]
then
	panic "suite unset in launcher.conf"
fi

echo deb $mirror $suite main > /etc/apt/sources.list.d/os-museum.list

if ! apt-get update
then
	panic "could not update package lists"
	exit 1
fi
if [ "$1" = "-c" ]
then
	if apt-get install --dry-run "$META_PACKAGE" | grep -q "$META_PACKAGE is already the newest version"
	then
		exit 2
	else
		if [ "${PIPESTATUS[0]}" -ne "0" ]
		then
			exit 1
		else
			exit 0
		fi
	fi
else
	apt-get install "$META_PACKAGE" && sudo rm -f /var/cache/apt/archives/*.deb
fi
