#!/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_FORCE=f
OPTS=:${OPT_INSTALL}${OPT_HELP}${OPT_FORCE}
USAGE="\
cloud-install [-${OPT_INSTALL}${OPT_HELP}${OPT_FORCE}]

Create an Ubuntu Cloud! (requires root privileges)

Options:
  -$OPT_INSTALL  install only (don't invoke cloud-status)
  -$OPT_HELP  print this message
  -$OPT_FORCE  bypass any sanity checks"

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_FORCE)
		force_install=true
		;;
	\?)
		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

createTempDir
startLog

trap exitInstall EXIT
trap "" PIPE

# TODO add better logging
set -x

#disableBlank

if [ -d /home/$INSTALL_USER/.juju ] && [ -z "$force_install" ]; then
	echo "You've already got juju configured! Aborting..." && exit 0
fi

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

	mkdir -m 0700 "/home/$INSTALL_USER/.cloud-install" || true
	echo "$openstack_password" > "/home/$INSTALL_USER/.cloud-install/openstack.passwd"
	chmod 0600 "/home/$INSTALL_USER/.cloud-install/openstack.passwd"
	chown -R "$INSTALL_USER:$INSTALL_USER" "/home/$INSTALL_USER/.cloud-install"

	case $install_type in
	Multi-system)
		multiInstall
		;;
	"Single system")
		singleInstall
		;;
	"Landscape managed")
		landscapeInstall
		;;
	*)
		# install cancelled by user
		exit 0
		;;
	esac
	touch /etc/.cloud-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
