#!/bin/ksh -p
#
# ident "@(#)utsetup.ksh	1.8	11/10/21 Oracle"
#
# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
#

PATH=/usr/bin:/bin:/usr/sbin:/sbin
OPTSBIN=/opt/SUNWut/sbin
PROGRAM_ID="$(basename $0)"
PROGRAM_DIR="$(dirname $0)"
ERROR_FILE=$(mktemp /tmp/${PROGRAM_ID}.errcode.XXXXXX)

function usage {
	typeset fd=$1

	print  "Usage: $PROGRAM_ID [options]
	-n		non-interactive (abort if input is required)
	-a		use auto-response file where possible
	-d		use auto-defaults file where possible
	-D dialog_dir	use dialog files in specified directory

	If -a and -d are both specified, auto-response entries take precedence.
" 1>&$fd
}

function LogIt {
	print ""
	print "=================================================================="
	print "=== $1 ==="
}

function do_utinstall {
	LogIt "Installing Sun Ray Software - utinstall"
	AICOPTS="${autoFlag:+-A} ${defaultFlag:+-c} $nonInteractiveFlag ${dialogDir:+-D $dialogDir}"
	$PROGRAM_DIR/utinstall $AICOPTS
}

function cleanup {
    rm -f $ERROR_FILE
}

function main {
	#
	# By default, the following programs will be executed in order:
	# utinstall *
	# utconfig * ***
	# utpolicy -x * ***
	# utreplica (if FOG was specified to utconfig) * ***
	# utfwadm -A -a -V ** ***
	# utadm -L on ** ***
	# utstart -c
	#
	# *  These programs have AIC-capable dialogs
	#
	# ** These programs will only be executed if requested (AIC-capable)
	#
	# *** These programs will only be executed for a fresh installation
	#

	do_utinstall
	STATUS=$?
	if [ $STATUS != 0 ]; then
	    echo $STATUS > $ERROR_FILE
	    exit $STATUS
	fi
	
	# The SUNWuti utsetup completes the rest of the required tasks
	if [ -x $OPTSBIN/utsetup ]; then
	    $OPTSBIN/utsetup -C $autoFlag $defaultFlag $nonInteractiveFlag $shouldSkipPersonalizingFlag	
	    STATUS=$?
	    if [ $STATUS != 0 ]; then
		echo $STATUS > $ERROR_FILE		
	    fi
	    exit $STATUS	    
	fi
}

# main

# ensure the cleanup function gets invoked on any exit 
trap cleanup 0

autoFlag=
defaultFlag=
nonInteractiveFlag=
dialogDir=

while getopts :adD:hn opt; do
	case $opt in
		a)
			autoFlag=-a
			;;
		d)
			defaultFlag=-d
			;;
		D)
			dialogDir=$OPTARG
			;;
		h)
			usage 1
			exit 0
			;;
		n)
			nonInteractiveFlag=-n
			;;
		?)
			print -u2 "$PROGRAM_ID: Unknown option '$OPTARG'"
			usage 2
			exit 1
	esac
done

if [ $# -ne $(( $OPTIND - 1 )) ]; then
	print -u2 "$PROGRAM_ID: Too many arguments"
	usage 2
	exit 1
fi

case $(uname -s) in
	SunOS) ADM_LOG_DIR="/var/adm/log";;
	Linux) ADM_LOG_DIR="/var/log";;
esac

TIME_STAMP="$(date '+%Y_%m_%d_%H:%M:%S')"
LOGFILE="${ADM_LOG_DIR}/${PROGRAM_ID}.${TIME_STAMP}.log"

main 2>&1 | tee $LOGFILE
#
# As main is in pipe with tee, we never get the exit code of it
# (we get the one from tee instead, which is always 0). The main procedure,
# then, creates a temporary file ($ERROR_FILE) which contains the error code
# of main. 

if [[ -f $ERROR_FILE ]]; then
   exit $(cat $ERROR_FILE)
fi
exit 0 
