#!/usr/bin/ksh93

#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# =============================================================================
# install_vm : Install a Virtual Machine
# =============================================================================
#

#
# Establish PATH for non-built in commands
#
export PATH=/usr/xpg4/bin:/bin:/usr/bin:/usr/sbin

#
# Source in shared common VMC code.
# All variable and functions defined in vmc_common are named with
# prifix "vmc" or VMC.
#
. /usr/share/distro_const/vmc/vmc_common

#
# Make sure all math stuff runs in the "C" locale
#
vmc_set_locale

#######################################################################
# cleanup
#	This function attempts to clean up any resources this script
#	could generate. Depending on where in the script this function
#	is involved some resources may not be there to cleanup, but
#	that will not adversely effect anything.
#
#	This function is not defined using the function keyword
#	to avoid an exit loop.
#
# Input: none
# Returns: none
#
#######################################################################
cleanup ()
{

	#
	# It is not necessary to process errors.
	#
	{

		trap "" ERR INT
		set +o errexit

		VBoxManage -q controlvm ${DIST_NAME} poweroff

	} > /dev/null 2>&1

}

#######################################################################
# main
#
# Args:
#	MFEST_SOCKET: Socket to get manifest data via ManifestRead object
#	PKG_IMG_PATH: Package image area
#	TMP_DIR: Temporary directory to contain the bootroot file
#	BR_BUILD: Area where bootroot is put together (not used)
#	MEDIA_DIR: Area where the media is put. (Not used)
#
# Inputs will be taken from the VMC Manifest:
#	<DIST_NAME> - "name" tag from VMC Manifest
#
# Output:
#
#	No formal output. (Result is a install VM instance.)
#
# Diagnostic Output:
#
#	Message written to standard output (print -u1) will go to
#	the distro constructor log file.
#
#	Message written to standard error (print -u2) will go to
#	the distro constructor log file and the screen where the
#	distro constructor is being run.
#
# Description:
#
#	This script will boot the virtual machine. The loaded
#	bootable automated installer will perform an installation.
#
#	Monitoring will be limited to what is provided by the AI client.
#	It is expected that at a minimum the AI client will need some
#	method to communicate that the install has completed for failed.
#
#	The VM interface to check if a VM has been shutdown will be used
#	to confirm when the install has completed.

# Returns:
#	1 on failure
#	0 on success
#
#######################################################################

builtin cp
builtin mkdir
builtin mv
builtin rm

#
# Variable which act as constants are in CAPs
# Variable which can be modified are in lower case
#
typeset -i  cmdsts
typeset    vbox_cmd

typeset -r  MANIFEST_READ=/usr/bin/ManifestRead
typeset -ri SLEEP_TIME=10
typeset     is_running="" # Used for testing if the VM is already running.

#
# Process command line arguments
#
if (( $# != 5 )) ; then
	print -u2 "\nWrong number of arguments provided by Distro Constructor."
	exit 1
fi

typeset -r MFEST_SOCKET="$1"

#
# Read the distribution name tag from the 
#
typeset -r DIST_NAME="$(${MANIFEST_READ} ${MFEST_SOCKET} "name")"

if [ "XX${DIST_NAME}" == "XX" ] ; then
        print -u2 "\nThe distribution name ${DIST_NAME}" \
            "is not valid"
        exit 1
fi

#
# Set up error handling.
# Where possible explicitly check command return status for errors.
#
trap "vmc_error_handler_trap Interrupt encountered. Exiting" INT
set +o errexit

#
# Check if VirtualBox is installed
#
vmc_is_vbox_installed
cmdsts=$?
vmc_error_handler ${cmdsts} \
    "\nError: Required VirtualBox version is not installed"

#
# Start the VM causing the bootable AI image to perform an install
#
vbox_cmd="VBoxHeadless -startvm ${DIST_NAME}"
print -u1 "\nInvoking: ${vbox_cmd}"
${vbox_cmd} 
cmdsts=$?
vmc_error_handler ${cmdsts} "\nError: ${vbox_cmd} failed"

#
# Give the VM a few seconds to start up before polling
#
sleep ${SLEEP_TIME}

#
# Loop while the VM's State is running
#
vbox_cmd="VBoxManage -q showvminfo ${DIST_NAME}"
is_running=$(${vbox_cmd} | grep "^State")
while [[ "${is_running}"  == ~(E)^State:[ ]*running.* ]]; do
	sleep ${SLEEP_TIME}
	is_running=$(${vbox_cmd} | grep "^State")
done        

#
# Did the VM power off completely
#
vm_state=$(${vbox_cmd} | grep "^State")
if [[ "${vm_state}" != ~(E)^State:[ ]*powered[ ]off.* ]]; then
	#
	# Force state to poweroff
	#
	vbox_cmd="VBoxManage -q controlvm ${DIST_NAME} poweroff"
	print -u1 "\nInvoking: ${vbox_cmd}"
	${vbox_cmd}
	cmdsts=$?
	vmc_error_handler ${cmdsts} "\nError: ${vbox_cmd} failed"
fi

#
# exit with success status
#
exit 0

