#!/bin/bash
#This script checks if the packages for a _config directory have been downloaded
#and optionally installs them.
#
#If the -c option is specified, this script will return exit code 2 if the
#package needs to be installed, and 0 if it is already installed. All failures
#currently return 1. If -c isn't specified, this will install the package if
#it currently isn't installed (however, it won't upgrade to the latest version
#if a previous version is already installed).
#
#If this isn't being run on the OS museum VM it will fail if -c isn't specified.
#If -c is specified when not running on the OS museum VM, it will always exit
#with 0.

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

if [ x"$1" = "x-c" ]
then
	check_only=true
	shift
fi

if [ x"$@" = x ]
then
	echo "usage: $0 [-c] <config directory>" >&2
	panic "$0: no installation specified"
fi

case "`echo $OSM_FORCE_NO_DOWNLOAD | tr A-Z a-z`" in
	1|true)
		exit 0
		;;
	*)
		;;
esac

if ! is_os_museum_vm
then
	if [ "$check_only" ]
	then
		exit
	else
		panic "This script can only be run on the OS Museum VM"
	fi
fi

if [ ! -d "$1" ]
then
	panic "$1 not a directory"
fi

package_name="`realpath $1`"
package_name="`basename $package_name`"

if ! echo $package_name | grep -q '_config$'
then
	panic "$1 does not have a name ending in _config"
fi

package_name="`echo $package_name | sed 's/_config$//g'| tr '_' '-'`"

if echo $package_name | grep -q "[^0-9a-z.+-]"
then
	panic "Invalid characters in machine config directory name $1"
fi

package_name="os-museum-machine-$package_name-image"

if [ "`dpkg-query -W -f '${Status}\n' $package_name 2>/dev/null`" == "install ok installed" ]
then
	exit
fi

if [ "$check_only" ]
then
	exit 2
fi

run_terminal_if_needed "$@"

set -e
set_mirror_from_config
sudo apt-get update
sudo apt-get -y install "$package_name"
