#!/usr/bin/ksh
################################################################################
#Copyright 2009,2012 Oracle and/or its affiliates.  All rights reserved.
#
# Usage options:
# -t, --tty 		(for starting with tty interface) 
# -c, --commandline	(for using the command line)
# -g, --gui		(for starting with standalone gui interface)
# -a, --all		(Start VTS all level testing )
# -h, --help		(help)
# -d, --default		(Start VTS default testing)
# -l, --long		(Start VTS Comprehensive testing)
# -s, --short		(Start VTS Short Testing)
# -m, --memory		(Start VTS Memory Testing)
################################################################################

PATH=/usr/bin:/usr/sbin:$PATH

#check if user is a valid user for accessing VTS
userAuth()
{
	userinfo=`id | awk '{print $1}'`
	#echo $userinfo

	userinfo=`echo $userinfo | awk '{i=index($1,"(");j=index($1,")");print substr($1,i+1,j-i-1)}'`

	#echo  $userinfo
	if [ "$userinfo" != "root" ]; then
		echo "Access Denied. You need root or superuser privileges."
		exit -4
	fi

}

userAuth;

SUCCESS=0
FAIL=1

#Get hostname and domainname
hostName=`hostname`
domainName=`domainname| awk '{i = index($0,".");print substr($0,i+1)}'`

#Get IP Address
#ipAddr=`ping -s $hostName 16 1|grep $hostName|grep -v PING|awk '{i=index($5,"(");j=index($5,")");print substr($5,i+1,j-i-1)}'`


#Path to Verbose logs
VTSLOGDIR='/var/sunvts/logs'
#checks if intermediate directories exists otherwise creates them.
mkdir -p $VTSLOGDIR;
#File for  Verbose logs
logfile=$VTSLOGDIR/sunvts.startup

echo "___________________________________________">>$logfile
echo "STATUS MESSAGES FOR  startsunvts       ">>$logfile
echo "------------------------------------------">>$logfile

#Get sunvts bin folder path from 
# 1. Environment Variable 
# OR
# 2. use dirname to get absolute or relative path

# Check if location of usr/sunvts/bin is set in PATH env variable
getEnvPath=`echo $PATH|grep /usr/sunvts/bin`

#If PATH var is set, extract the the complete path to sunvts/bin folder
#Otherwise, assume that user executed script with complete or relative path. 
if [ -n "$getEnvPath" ]; then
	echo "PATH env variable is: "$getEnvPath"User had manually set the path">>$logfile
	getSunvtsPath=`echo $getEnvPath|awk '{n=split($0,pathArray,":");
	for(i=1;i<=n;i++)
	{
		$1=index(pathArray[i],"/usr/sunvts/bin")
		if($1 != 0)
			break;
	}
	print pathArray[i]}'`

else 
	echo "PATH env variable not set by user. Absolute or relative path provided to execute script">>$logfile
	case $0 in
	/*)
 	   getSunvtsPath=$(dirname $0)
	;;
	
	*)
	   getSunvtsPath=$(pwd)/$(dirname $0)
	   getSunvtsPath=`(cd ${getSunvtsPath};pwd)`
	;;
	esac
fi

#path to {root_dir}/usr/sunvts/bin
binPath=$getSunvtsPath
echo "Complete path to /usr/sunvts/bin folder is: "$binPath>>$logfile


#check if vts.pid file exits.
#If yes, then match the pid in file to vtsk process id
getvtsk_pid()
{
checkvtsk_ps="";
checkvtsk_vtspid="";
#check for vts.pid file. If it exists, get the vtsk process id.
if [ -r /var/sunvts/vts.pid ] ; then
            checkvtsk_vtspid=`cat /var/sunvts/vts.pid | egrep -v VTS_PID `

checkvtsk_ps=`ps -ef | grep sunvts/bin | grep vtsk | egrep -v grep | awk '{print $2}'`
if [ -z "$checkvtsk_ps" ]; then
checkvtsk_ps=`ps -ef | grep ./vtsk | egrep -v grep | awk '{print $2}'`
fi

#compare the two vtsk pids
if  [ "$checkvtsk_vtspid" -eq "$checkvtsk_ps" ]; then
	return $SUCCESS;
fi
else 
	return $FAIL;
fi
}

# Check which version of vtsk is running. If the version is 
# anything before 7.0 then exit the startsunvts script. 
checkVtskVersion()
{

#echo "Checking agent version . . ."
sleep 3;
getvtsk_pid

#if [ "$?" = "$SUCCESS" ]; then
        checkVtsk="$checkvtsk_ps";
#fi

if [ -n "$checkVtsk" ]; then
	agent_version=`$path/usr/sunvts/bin/vts_cmd get_version`
	which_version=`echo $agent_version | awk '{print substr($0, 0, 1)}'`
	if [ -z "$which_version" ] || [ "$agent_version" = "ERROR: host is down or does not exist" ]; then
       		 echo "Another instance of vtsk is quitting, or vtsk did not start. \nPlease try again. \nExiting startsunvts . . ."
               exit 1
         fi

	if [ "$which_version" = "E" ] || [ "$which_version" -lt "7" ]
	then
		echo "A version of VTS agent lower to 7.0 is running on the host.\nstartsunvts can be executed with VTS 7.0 or higher version.\nExiting startsunvts ..."
		exit 1
	fi
fi
}

# Check if vtsk is idle
is_vtsk_idle()
{
sleep 5;
getvtsk_pid

#if [ "$?" = "$SUCCESS" ]; then
        checkVtsk="$checkvtsk_ps";
#fi


if [ -z "$checkVtsk" ]; then
return
fi

vtskstatus=`$binPath/vts_cmd get_status | cut -d "/" -f1`

if [ -n "$vtskstatus" ]; then
	if [ "$vtskstatus" != "idle" ]; then
	echo "Testing. status is not idle"
	echo "Cannot proceed with " $1
	echo "Please try later. Exiting now."
	exit 1;
	fi
fi

}

#Documents for more information
docs()
{
	echo >&2 "For additional information, please refer to any of the following documents:"
	echo >&2 "1. Check logs at " $VTSLOGDIR
	echo >&2 "2. README file located at /usr/sunvts"
	echo >&2 "3. Online documents available at http://docs.sun.com. Please search for VTS 7.0"
}

#Starts Agent and TTY UI
tty()
{
	checkVtskVersion;
	#docs
	echo >&2 "Starting VTS TTY UI......">>$logfile
	$binPath/invokeVtsAgent -k>>$logfile
	$binPath/vtstty


}
gui()
{
	if [ -z $DISPLAY ]
	then
		echo "\nPlease set DISPLAY variable. \nExecute 'xhost +' on target machine.\nRe-run the startsunvts script."
		exit 1
	fi

	#get java version
	javaversion=`java -version 2>&1|cut -s -d '"' -f2|cut -d "." -f2`
	if [ ${javaversion:=0} -lt 5 ]; then
		echo "Please check Java version. \nIt should be 1.5 or higher.\nCurrent version of Java is 1.$javaversion \nAlso, check if java is set in path"
	exit 1;
	fi

	checkVtskVersion
	#docs
	echo >&2 "Starting VTS GUI......">>$logfile
	$binPath/invokeVtsAgent -k>>$logfile
	$binPath/invokeGui &
}

#If exit from runvts due to non-idle vtsk, check it and exit from the script
is_system_under_test()
{
 	if [ $2 -eq 1 ]; then
 	echo "\nTesting status is not idle."
 	echo "Cannot proceed with " $1
 	echo "Please try later. Exiting now."
 	exit 1
 	fi

	if [ $2 -eq 2 ]; then
	echo "\nVTS agent has quit."
	echo "Cannot proceed with testing." 
	echo "Please try later. Exiting now."
	exit 1
	fi

	if [ $2 -eq 3 ]; then
         echo "Cannot continue.\nNo tests are available for run."
        exit 1
        fi

}


#
#VTS should go ahead and run 2 hours of Exerciser (high)
#      and 1 pass of Component Stress (high).
default()
{
	checkVtskVersion;
	is_vtsk_idle "Default Testing"
	$binPath/runvts -l4 -L4 -t120
	is_system_under_test "Default Testing" $? 
	sleep 120
	$binPath/vtsreportgenerate -s	
	sleep 10
	$binPath/runvts -l6 -L6 -p1

	is_system_under_test "Default Testing" $?
	
	sleep 120
	$binPath/vts_cmd quit
	sleep 10
	$binPath/vtsreportgenerate -s	
}
#
#Run the Exerciser Mode for 30 mins.
#
short()
{
	checkVtskVersion;
	is_vtsk_idle "Short Testing"
	$binPath/runvts -l4 -L4 -p0 -t30
	is_system_under_test "Short Testing" $?	
	sleep 120
	$binPath/vts_cmd quit
	sleep 120
	$binPath/vtsreportgenerate -s	
}
#
#
##Run the default settings of the tool. Exerciser Mode
# (high) for 4 hours, then Component Stress for 5 passes.

long()
{
	checkVtskVersion;
	is_vtsk_idle "Comprehensive Testing"
	$binPath/runvts -l4 -L4 -p0 -t240
	is_system_under_test "Comprehensive Testing" $?
	sleep 120
	$binPath/vtsreportgenerate -s	
	sleep 10
	$binPath/runvts -l6 -L6 -p5
	is_system_under_test "Comprehensive Testing" $?	
	sleep 120
	$binPath/vts_cmd quit
	sleep 10
	$binPath/vtsreportgenerate -s	
}
#
# Run Exerciser Mode for 1 hour. Run
# Interconnect LT and Memory LT for 1 pass in the CS mode.
#
memory()
{
	checkVtskVersion;
	is_vtsk_idle "Memory Testing"
	$binPath/runvts -l4 -L4 -p0 -t60
	is_system_under_test "Memory Testing" $?
	sleep 120
	$binPath/vtsreportgenerate -s	
	sleep 10
	$binPath/runvts -l6 -L6 -p1 MLT ILT	
	is_system_under_test "Memory Testing" $?
	sleep 120
	$binPath/vts_cmd quit
	sleep 10
	$binPath/vtsreportgenerate -s	
	sleep 10
}
# Testing all levels in one command.
#
all() {
	checkVtskVersion;
	is_vtsk_idle "All Testing"
	$binPath/runvts -l1 -L6 -t240
	is_system_under_test "All Testing" $? 
	sleep 120
	$binPath/vts_cmd quit
	sleep 10
	$binPath/vtsreportgenerate -s
	sleep 10
}

#Help for user
usage()
{
#echo >&2 "\n"
echo >&2 "Usage: $binPath/startsunvts [options]"
echo >&2 "      where [options] can be any of the following:"
echo >&2 "      -t, --tty			Start TTY UI"
echo >&2 "      -c, --commandline		Use Command Line"
echo >&2 "      -g, --gui                       Start VTS GUI"
echo >&2 "      -a, --all		Start VTS all level testing"
echo >&2 "      -d, --default 		Start VTS default testing "
echo >&2 "      -l, --long		Start VTS Comprehensive testing "
echo >&2 "      -s, --short		Start VTS Short Testing "
echo >&2 "      -m, --memory		Start VTS Memory Testing "
#echo >&2 "      -B, --BootCD		Start TTY UI in BootCD"
echo >&2 "      -h, --help		Display help list"
}

#checkVtskVersion

#Handling different scenarios for running VTS 7.x
#Check which option provided by the user. 
while getopts :"t(tty)""c(commandline)""a(all)""h(help)""B(BootCD)""g(gui)""d(default)""l(long)""s(short)""m(memory)" option

do 
	case "$option" in
	t)
	echo >&2 "Starting TTY UI...."
	tty	
	exit 1;;
	c)
	echo >&2 "Initializing Command Line UI..."
	checkVtskVersion	
	$binPath/invokeVtsAgent -k>>$logfile 
	echo >&2 "DONE"
	#docs
	exit 1;;
	a)
	echo >&2 "Starting VTS all level testing..."	
	all
	exit 1;;
	B)	
        echo >&2 "Starting TTY UI in Bootable CD.."
	tty
	exit 1;;	
	
	g)	
        echo >&2 "Starting GUI ......"
	gui
	exit 1;;	

	d)	
        echo >&2 "Starting VTS Default Testing ......"
	default
	exit 1;;	

	l)	
        echo >&2 "Starting VTS Comprehensive Testing ......"
	long
	exit 1;;	

	s)	
        echo >&2 "Starting VTS Short Testing......"
	short	
	exit 1;;	
	m)	
        echo >&2 "Starting VTS Memory Testing ......"
	memory
	exit 1;;	
	
	h)
	usage
	exit 1;;
	?)
	echo >&2 "Invalid Option!!"
	usage
	exit 1;;
	esac
done

clear

#If no option then have interactive session with the user.
echo >&2 "Which VTS 7.0 User Interface (UI) or Testing option would you like to use?"
echo >&2 "a) Command Line Interface"
echo >&2 "b) Terminal User Interface"
echo >&2 "c) Graphical User Interface"
echo >&2 "d) Default Testing"
echo >&2 "l) Comprehensive Testing"
echo >&2 "s) Short Testing"
echo >&2 "m) Memory Testing"
echo >&2 "A) All level Testing"

read var1
#echo "var1 = $var1"

case "$var1" in
	a)
	 echo >&2 "Initiating Command Line UI..."
	$binPath/invokeVtsAgent -k>>$logfile 
	echo >&2 "DONE"
	#docs
	exit 1;;
	b)
	echo >&2 "Starting TTY UI...."	
	tty
	exit 1;;
	c)
	echo >&2 "Starting GUI...."	
	gui
	exit 1;;
	d)
	echo >&2 "Starting VTS Default Testing...."	
	default
	exit 1;;
	l)
	echo >&2 "Starting VTS Comprehensive Testing...."	
	long
	exit 1;;
	s)
	echo >&2 "Starting VTS Short Testing...."	
	short	
	exit 1;;
	m)
	echo >&2 "Starting VTS Testing for Memory...."	
	memory
	exit 1;;
	A)
	echo >&2 "Starting VTS all level Testing...."	
	all
	exit 1;;
	?)
	echo >&2 "Invalid Choice!!!"
	echo >&2 "Exited from script"
	exit 1;;
	*)
        echo >&2 "Invalid Choice!!!"
	echo >&2 "Exited from script"
        exit 1;;

esac
#exit 1;;

