#!/bin/sh -e
#
# cloud-install - Cloud installer
#
# Copyright 2014 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. /usr/share/cloud-installer/common/display.sh
. /usr/share/cloud-installer/common/common.sh
. /usr/share/cloud-installer/common/maas.sh
. /usr/share/cloud-installer/common/juju.sh
. /usr/share/cloud-installer/common/configure.sh
. /usr/share/cloud-installer/common/multi.sh
. /usr/share/cloud-installer/common/single.sh
. /usr/share/cloud-installer/common/landscape.sh

OPT_HELP=h
OPT_INSTALL=i
OPT_CONFIGFILE=c
OPTS=:${OPT_INSTALL}${OPT_HELP}${OPT_CONFIGFILE}:
USAGE="\
cloud-install [-${OPT_TYPE}${OPT_CONFIGFILE}${OPT_HELP}]

Create an Ubuntu Cloud! (requires root privileges)

Options:
  -$OPT_CONFIGFILE <file> - POSIX shell script to be sourced by installer
      automating install by pre-setting menu responses.
  -$OPT_INSTALL  install only (don't invoke cloud-status)
  -$OPT_HELP  print this message"

usage()
{
	echo "$USAGE"
}

usageError()
{
	echo "$1" >&2
	usage >&2
}

while getopts $OPTS opt; do
	case $opt in
	$OPT_INSTALL)
		install=true
		;;
	$OPT_HELP)
		usage
		exit 0
		;;
	$OPT_CONFIGFILE)
		configfile=$OPTARG
		;;
	\?)
		usageError "Unknown argument: $OPTARG"
		exit 1
		;;
	esac
done
shift $((OPTIND - 1))

if [ $(id -u) -ne 0 ]; then
	usageError "Installing a cloud requires root privileges. Rerun with sudo."
	exit 1
fi


if [ ! -z "$configfile" ]; then
    . $configfile
fi

createTempDir
startLog

trap exitInstall EXIT HUP INT QUIT TERM
trap "" PIPE

# TODO add better logging
set -x

disableBlank

mkdir -p /etc/cloud-installer

if [ ! -e /etc/cloud-installer/installed ]; then
	configureInstall

	case $install_type in
	Multi-system)
		multiInstall
		;;
	"Single system")
		singleInstall
		;;
	"Landscape managed")
		install=true # install only implied
		landscapeInstall
		;;
	*)
		# install cancelled by user
		exit 0
		;;
	esac
	touch /etc/cloud-installer/installed
else
	echo "Cloud already installed."
fi
if [ -z "$install" ]; then
	exitInstall
	cd "/home/$INSTALL_USER"; exec sudo -H -u "$INSTALL_USER" cloud-status
fi
