#!/bin/ksh
#
# Utilities.sh
#
# Useful functions used in other scripts
#
# Author: Alexandre W. Agostini
# Version: 1.0.0
# Date: 2006-08-14
#
# (c) Copyright 2007 Hewlett-Packard Development Company, L.P. 
#

# 16.127.36.227:/release/1123.0609/ic053b/perf/HPUX11i-OE-MC.ALL

trap clean_up_temps EXIT 
trap "" int

typeset    SOURCE_HOST=
typeset -r REMOTE_TEMP_DIR=/tmp/P2V
typeset -r ANALYZE_SCRIPT_NAME=$INC_PATH/analyzesys
typeset -r UTILITIES_SCRIPT_NAME=$INC_PATH/p2vcommon
typeset -r ANALYZE_RESULT_SUFFIX=phys_info
typeset -r PARAM_RESULT_SUFFIX=parameters

typeset -r STD_BOOT_TEMPLATE='P2VAPPTEMPL:ht=ethernet:hn:bf=/opt/ignite/boot/nbp.efi:bs=48:ci=\"PXEP2V\":vm=rfc1048:sm=0xfffffc00:'
typeset -r GUESTBOOTPARMS='%s:tc=P2VAPPTEMPL:ip=%s:ha=%s:'

typeset -r OS_EXCLUSION_BUNDLES_FILE=$INC_PATH/os_bundles_list.conf
typeset -r OS_EXCLUDE_LIST_FILE=$OS_EXCLUSION_BUNDLES_FILE'.tmp'

typeset -r SSH_OPTS='BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=5'
 

#-----------------------------------------------------------------------------
function check_root_user { 

root_id=0                # Users with UID 0 have root privileges.
user_id=`/usr/bin/id -u` # get the current user id

if [ "$user_id" -ne "$root_id" ]
then
     printf "\nMust have root privileges to run this utility.\n\n"
     exit 1
fi
}

#-----------------------------------------------------------------------------
function ShowError {

	msg=$1

	printf "\n\t $msg\n\n" 
	#printf "\tPress enter to continue: "
	#read dummy
}

#-----------------------------------------------------------------------------
function ReturnPrevious {
	
	RUN_CMD=return
}
#-----------------------------------------------------------------------------
function RunMenu { 

	printf "\n\n%s\n" "$MENU_TITLE"
	printf "======================================\n\n" 
	
	typeset opnum
	integer mn_str_ix=0
	while [ $mn_str_ix -lt ${#MENU_STR[*]} ]
	do
		opnum=$(echo ${MENU_OP[$mn_str_ix]} | cut -d, -f1)
		
		if [ $opnum = '-' ]
		then
			printf " -----\n"
		else
			printf ' %d ) %s\n' $opnum "${MENU_STR[$mn_str_ix]}"
		fi
		let mn_str_ix=$mn_str_ix+1
	done
	
	while true
	do
		printf "\nEnter Option Number: "
		read -r option_number
		echo $option_number | grep -q -E '^[0-9]+$'  || { printf "Please choose an option from the list."; continue ; }
		ValidadeOpNumber "$option_number" && { $RUN_CMD ; break ; }
	done
}

#-----------------------------------------------------------------------------
function ValidadeOpNumber {

	typeset Op="$1"
	typeset opnum
	integer mn_str_ix=0
	
	while [ $mn_str_ix -lt ${#MENU_STR[*]} ]
	do
		opnum=$(echo ${MENU_OP[$mn_str_ix]} | cut -d, -f1)
		
		if [ $opnum = "$Op" ]
		then
			RUN_CMD=$(echo ${MENU_OP[$mn_str_ix]} | cut -d, -f2)
			return 0
		fi
		let mn_str_ix=$mn_str_ix+1		
	done	
	printf "Invalid option (%d)\n" $Op
	return 1
}

#-----------------------------------------------------------------------------
function MainMenu {

while true
do
	clear
	typeset MENU_TITLE='P2V Assistant Manager'

	set -A MENU_STR              \
		'General Configurations' \
		'Manage Applications'    \
		'Manage O.S. Images'     \
		'-'                      \
		'Exit'
	
	set -A MENU_OP         \
		1,GeneralConfig    \
		2,ManAppCandidates \
		3,ManOsImage       \
		-,-                \
		0,ExitProg

	RunMenu
done

}

#-----------------------------------------------------------------------------
function GeneralConfig {
 
	while true
	do
		MENU_TITLE='General Configurations'
		
		set -A MENU_STR                   \
			'Set Source Depot'            \
			'-'							  \
			'Return'
		
		set -A MENU_OP                   \
		    1,SetSourceDepot             \
			-,-                          \
		    0,ReturnPrevious
		
		RunMenu
		if [ $RUN_CMD = return ]; then break; fi
	done 
 
}

#-----------------------------------------------------------------------------
function ManOsImage {

	printf '\n\tFeature not available yet.\n\n'
	prompt_AnyKey
}

#-----------------------------------------------------------------------------
function ManAppCandidates { 

	while true
	do
		MENU_TITLE='Manage Applications'
		
		set -A MENU_STR                   \
			'List Applications'           \
			'Select Applications'         \
			'Add Data Directories/Files'  \
			'Consolidate Applications'    \
			'-'							  \
			'Return'
		
		set -A MENU_OP                   \
			1,ListApplicationCandidates  \
		    2,SetApplicationCandidates   \
		    3,AddDataDirectories         \
			4,ConsolidateApplication     \
			-,-                          \
		    0,ReturnPrevious
		
		RunMenu
		if [ $RUN_CMD = return ]; then break; fi
	done
}

#-----------------------------------------------------------------------------
function ConsolidateApplication {

	clear
	#--------------------------------------------------------
	printf '\n\n'
	printf '
	  Consolidate Applications'
	printf '
	==============================\n'
	printf '	
	This option will consolidate application(s) installed 
	on the current system and then migrate into another a
	suitable target system. The target system is the machine
	which will host the consolidated application(s). 
	This wizard requires that non-interactive Secure Shell
	(ssh) access be set up between this system and the 
	target server.\n\n'

	printf "\n\tDepots source currently configured: ${depot_server} \n\n"
	
	ERROR=0
	if [ ! "${depots_array[*]}" ]
	then
		printf "	Depot list not defined.\n\n"
	else
		printf "	Depots to be installed: %s\n\n" "${depots_array[*]}"
	fi

	if [ ! "${dirs_array[*]}" ]
	then
		printf "	Dirs/Files list not defined.\n\n"	
	else
		printf "	Dirs/Files to be transferred: %s\n\n" "${dirs_array[*]}"
	fi

	if [ ! "${depots_array[*]}" ] && [ ! "${dirs_array[*]}" ]
	then
		printf '	
	Please configure at least one application depot or 
	application data directory.\n\n'
		prompt_AnyKey
		return 0
	fi	

	while true
	do
		printf "\tPlease enter the hostname/IP \n\tof the target system (type 'q' to return): "
		read -r target_host
		echo $target_host | grep -q -E "^[A-Za-z0-9._-]*$" || { ShowError "Invalid host name." ; continue ; }		
		[ -z "$target_host" ]    && { continue ; }
		[ "$target_host" = 'q' ] && { return 0 ; }
		
		printf "\tQuerying the system %s for current status,\n\tthis may take a few moments...\n" $target_host
		check_ssh_connectivity $target_host || { ShowError "It was not possible to connect to host $target_host." ; 
												continue ; }
												
		TARGET_HOST=$(ssh -l root -o $SSH_OPTS $target_host "uname -n")
		SOURCE_HOST=$(uname -n)
		[ $SOURCE_HOST = $TARGET_HOST ] && { ShowError "Cannot use same host as source and target." 
											continue ; }
		break
	done

	Install_App_Status=0;
	#[ -n "${depots_array[*]}" ] && { SD_array=$depot_server	
	#									Install_Application ;
	#									Install_App_Status=$? } 
	if [ -n "${depots_array[*]}" ] 
	then 
		SD_array=$depot_server	
		Install_Application 
		Install_App_Status=$?
	fi


	if [ $Install_App_Status = 0 ]
	then
	
	prompt_AnyKey
	printf "\tTransferring Configuration files...\n"
	Copy_Application_Files
	printf "	Application Sucessfully consolidated on host: %s\n\n" $target_host
	fi

	printf "	Press <Enter> to return to menu:"
	read -r go_on	
}


#-----------------------------------------------------------------------------
# OS_EXCLUSION_FILE file containig the list of Bundles to exclude from the 
#					swlist output for the user to choose.
function ListApplicationCandidates {
	
	Bundle_Exclusion_List=$(cat $OS_EXCLUSION_BUNDLES_FILE)
	
	swlist -l product $Bundle_Exclusion_List 2> /dev/null | 
		grep -v -e "^#" -e "^$" | awk '{ split($0,sw,"\.| +|\t+"); print sw[3]; }' > $OS_EXCLUDE_LIST_FILE
		
	swlist -l product 2> /dev/null | grep -v -e "^#" -e "^$" -e "(^#|PH[A-Z]{2}_[0-9]+)" | 
				grep -v -f $OS_EXCLUDE_LIST_FILE | more -d
				
	rm $OS_EXCLUDE_LIST_FILE
	return 0
}

#-----------------------------------------------------------------------------
function SetApplicationCandidates {

	clear
	#--------------------------------------------------------
	printf '\n\n'
	printf '\t  Select Applications\n'
	printf '\t==============================\n'


	if [ -z "$depot_server" ]
	then
		printf "\tThere's no source depot server defined.\n\tPlease define one before selecting the application depots."
		SetSourceDepot || { ShowError "The source depot was not defined. Cannot proceed." ; return 1 ; }
	fi

	printf "
	Please enter the list of depots to be installed on the target
	system, separated by spaces. 
	
	WARNING: OS related products must not be selected. Only applications 
	may be selected. Migrating OS related depots may damage target host.
	
	You can list the applications using the first option of this menu.\n\n"
	while true
	do
		printf "\tDepots list (type \'q\' to return): "
		read -r depot_list
		#echo $depot_list | grep -q -E "^/[A-Za-z0-9.]+[A-Za-z0-9./]*$" || { ShowError "Invalid name for file or directory." ; return 1 ; }		
		for i in $depot_list
		do
			#echo $depot_list | grep -q -E "^[A-Za-z0-9._+-]*$" || { ShowError "Invalid depot name." ; continue ; }		
			echo $i | grep -q -E "^[A-Za-z0-9._+-]*$" || { ShowError "Invalid depot name." ; continue ; }		
		done
			[ "x$depot_list" = 'xq' ] && { return 0 ; }
			[ ! "x$depot_list" = 'x' ]   && { ValidateDepotList "$depot_list" && { return 0 ; } ;}
	done
	return 0
}

#-----------------------------------------------------------------------------

# set -A vm_host      `parse_param_file_keyword $PARAMETER_FILE_NAME vmhost`
# set -A source_host  `parse_param_file_keyword $PARAMETER_FILE_NAME sourceserver`
# set -A target_host  `parse_param_file_keyword $PARAMETER_FILE_NAME targetvm`
	
# set -A files_array  `parse_param_file_keyword $PARAMETER_FILE_NAME file`
# set -A dirs_array   `parse_param_file_keyword $PARAMETER_FILE_NAME dir`
# set -A disks_array  `parse_param_file_keyword $PARAMETER_FILE_NAME disk`

# set -A install_array `parse_param_file_keyword $PARAMETER_FILE_NAME installscript`
# set -A depots_array  `parse_param_file_keyword $PARAMETER_FILE_NAME swcomponent`
# set -A IUX_array     `parse_param_file_keyword $PARAMETER_FILE_NAME iuxserver`
# set -A SD_array      `parse_param_file_keyword $PARAMETER_FILE_NAME depotserver`

#-----------------------------------------------------------------------------
function ValidateDepotList {
	
	dep_lst=$1
	
	for dep in $dep_lst
	do
		swlist -l product  $dep > /dev/null 2>&1 || { ShowError "\tThe $dep depot was not found in this host." ; return 1 ; }
		swlist -l product  -s $depot_server $dep > /dev/null 2>&1 || { ShowError "\tThe $dep depot was not found on the \n\tconfigured depot source server: $depot_server" ; return 1 ; }
	done
	
	set -A depots_array $dep_lst
	return 0
}

#-----------------------------------------------------------------------------
# Return a list of directories from a set of depots informed
function GetDirFromDepots {

	#dirs_sugest=$(swlist -a directory -l product  $depots_array | 
	dirs_sugest=$(swlist -a directory -l product   ${depots_array[*]} | 
		grep -v -e "^#" -e "^$" | awk '{ print $2 }' | 
		sort | uniq)
}
#
#-----------------------------------------------------------------------------
#
function AddDataDirectories {
	printf "
	Please enter the list of directories/files to be transferred to the 
	target system, separated by spaces.\n"
	
	if [ -n "$depots_array" ]
	then
		GetDirFromDepots
		printf "\tThe following directories are obtained by examining the depot configuration,\n\tyou may copy them to the prompt below in order to be used:\n\n$dirs_sugest\n\n"
	fi
	
	while true
	do
		printf "\tDirectories/Files list (type \'q\' to return): "
		read -r dirs_files_list
		[ "x$dirs_files_list" = 'xq' ] && { return 0 ; }
		[ ! "x$dirs_files_list" = 'x' ]   && { ValidateDirsFilesList "$dirs_files_list" && { return 0 ; } ;}
	done

	return 0
}

#-----------------------------------------------------------------------------
# Check if any informed path is neither a file or a directory.
function ValidateDirsFilesList {

	array_check=$1

	for object in $array_check
	do
		echo $object | grep -q -E "^/[A-Za-z0-9._-]+[A-Za-z0-9._/-]*$" || { ShowError "Invalid name for file or directory." ; return 1 ; }
		
		case $object in
			/ |	/var |	/opt | /usr |/tmp) ShowError "Error: Cannot use $object as a data directory."
					return 1
				;;
		esac
		
		IS_FILE=0
		IS_DIR=0
		[[ -f $object ]] && { IS_FILE=1 ; }
		[[ -d $object ]] && { IS_DIR=1  ; }		
		[[ $IS_FILE = 0 && $IS_DIR = 0 ]] && { ShowError "Error: $object does not exists." ; return 1 ; }
	done

	set -A dirs_array $array_check
	return 0
}

#-----------------------------------------------------------------------------
function SetSourceDepot {
	printf "
	In this option you can set the location of the depots
	of the application to be installed on the target system.
	It can be a hostname or a local directory.\n"
	
	
	printf "\n\tDepots source currently configured: ${depot_server:=NONE}\n"
	
	while true
	do
		printf "\n\tDepots source (type \'q\' to return): "
		read -r dpt_srv
		echo $dpt_srv | grep -q -E "^[A-Za-z0-9._:/-]*$" || { ShowError "Invalid depot source name." ; continue ; }		
		[ -z "$dpt_srv" ]    && { continue ; }
		#[ "x$dpt_srv" = 'xq' ] && { break ; }
		[ "x$dpt_srv" = 'xq' ] && { depot_server=;return 1 ; }
		
		swlist -s $dpt_srv > /dev/null 2>&1
		if [ $? = 0 ]
		then
			depot_server=$dpt_srv
			return 0
		else
			printf "\n\tInvalid depot source."			
		fi
	done
}

#-----------------------------------------------------------------------------
function ExitProg {

	exit 0	
}

#-----------------------------------------------------------------------------
# $1 - Message to display in the bottom line.
# $2 - (optional) COMMENT : Prefix comment char on lines.
function printHeader {
    
	if [ "$2" ]; then comment="# " ; else comment=""; fi

    clear
    printf "%s+------------------------------------------------+\n" "${comment}"
    printf "%s|                                                |\n" "${comment}"
    printf "%s|         "
    tput smso               # "start mode shift out": usually reverse
    printf "Physical to Virtual Assistant"
    tput rmso               # "reset mode shift out"
    printf "          |\n" "${comment}"
    printf "%s|        -------------------------------         |\n" "${comment}"
    printf "%s|                                                |\n" "${comment}"
    printf "%s|                                                |\r" "${comment}"
    printf "%s|   %-30s\n" "${comment}" "$1"
    printf "%s+------------------------------------------------+\n" "${comment}"
    printf "%s\n"  "${comment}"
}


#-----------------------------------------------------------------------------
function clean_up_temps {
    typeset dummy
}


#-----------------------------------------------------------------------------
function com_get_system_name {
    if [[ -z "$SYSTEM_NAME" ]]
    then
        tmp=`hostname`
        SYSTEM_NAME=${tmp%%.*}
    fi
}


#-----------------------------------------------------------------------------
function get_board_params {
#  machinfo | grep Memory -> 		Memory = 12277 MB (11.989258 GB)
#  machinfo | grep "Number of CPUs" ->  Number of CPUs = 2

echo "# "
echo "# ------------------------------------------"
echo "#  Server System Parameters"
echo "# ------------------------------------------"
echo "# "
echo "# Created on "`date`
echo "# "
echo "# "

machinfo | awk ' /Memory/ { n=split($0, m, "[ =]*"); printf("MEM %s\n", m[2]) }
                 /Number of CPUs/ { n=split($0, m, "="); printf("CPU %s\n", m[2]) }
		'
}

#-----------------------------------------------------------------------------
function get_lan_cards {
	for lan_idx in `lanscan -p`
	do
		lan_status=`ifconfig 'lan'${lan_idx} 2>&1`
	        if [ $? -ne 0 ]
	        then
	        	IP="N/A"
	                NIC_STATE="N/A"
	        else
	        	NIC_STATE="DOWN"
	        	ifconfig 'lan'${lan_idx} | grep -q -E "flags=[0-9]+<UP.*" && NIC_STATE="UP"
	                IP=`ifconfig 'lan'${lan_idx} | grep inet | awk '{ print $2 }'`
	        fi
            #printf "NET %-5s %-18s %s\n" lan${lan_idx} ${IP} ${NIC_STATE}
	done
}

#-----------------------------------------------------------------------------
# Receives a mount point ex. /opt
# Returns a volume group ex. /dev/vg00 or a device id, ex. /dev/c0t0d0
function get_volume_from_mount {

mount | grep -E "^$1 on /.* " | awk '{ print $3 }' | awk -F/ ' { printf("/%s/%s\n", $2, $3) }'

}

#-----------------------------------------------------------------------------
# Receive a volume group or device id
# Return a list of the disks the vg is made of and their sizes. 
# If received the device id returns it along with its size.
function get_volume_details {

type=VG
echo $1 | grep -q -E "^/dev/dsk/c[0-9]+t[0-9]+d[0-9]+(s[0-9]+){0,1}$" && type=DISK

	case $type in
        	DISK) #echo "disk"
                ;;

        	VG) #echo "volume group"
          	vgdisplay -v $1 | grep 'PV Name' | grep -v 'Alternate Link' |
                awk '{printf ("%s\n", $3)}' |
                while read disk
                do
                     	echo $disk | awk '{ sub( "s[0-9]+", ""); print $0 }' | read disk
                	raw_ctd="`echo $disk | awk -F/ '{ printf ("/dev/rdsk/%s", $4) }'`"
                        diskinfo $raw_ctd | grep "size:" | read dummy disk_size unit
                        echo "DSK $disk $disk_size"
                done
        	;;
    esac
}

#-----------------------------------------------------------------------------
# isvalidip - is argument in "dotted decimal" format: xxx.xxx.xxx.xxx ?
function isValidIP { 
    typeset ip=$1             # ipaddr
    typeset ipv=              # IP address vector
    integer i=0

    # A valid IP address can only consist of decimal characters
    # separated by periods

	#[[ $ip == *[!0-9.]* ]] && return 1

    OIFS=$IFS; IFS="."
    set -A ipv -- $ip
    IFS=$OIFS

    # One to four parts, separated by a period
    (( ${#ipv[@]} < 1 || ${#ipv[@]} > 4 )) && return 1

    # Add "0" bytes to the end, if missing: "10" -> "10.0.0.0"
    ((i=0))
    while (($i < 4))
    do
        ipv[$i]=${ipv[$i]}
        ((i=$i+1))
    done

    # Each decimal byte must be in the range 0...255
    ((i=0))
    while (($i < ${#ipv[@]} ))
    do
        (( 0 <= ${ipv[$i]} && ${ipv[$i]} <= 255 )) || return 1
        ((i=$i+1))
    done
    return 0
}

#-----------------------------------------------------------------------------
function prompt_AnyKey {
	printf "Press <Enter> to continue.\n"
	read -r opt
}

#-----------------------------------------------------------------------------
function prompt_YesNo {
go_on=""
while [ ! "$go_on" ]
do
	printf "Enter option ([Y]es/[N]o) [y]? "
	read opt
        case "$opt" in
        	"") RESULT=YES
                go_on=go
                ;;

        	Y|y) 
                RESULT=YES
                go_on=go
                ;;
                        
        	N|n) 
                RESULT=NO
                go_on=go
                ;;

            *) echo "The option $opt is invalid."
               ;;
        esac
done
}

#-----------------------------------------------------------------------------
# Waits for the specified option, if success set variable RESULT to the option.
function prompt_next {

go_on=""
while [ ! "$go_on" ]
do
	echo "Enter option ([y]es/[s]kip/[q]uit)[y]?"
	read next
        case "$next" in
        	"") RESULT=YES
                go_on=go
                ;;

        	Y|y) 
                RESULT=YES
                go_on=go
                ;;
                        
        	s|S) 
                RESULT=SKIP
                go_on=go
                ;;
                        
        	Q|q) 
                RESULT=QUIT
                go_on=go
                ;;

            *) echo "The option $next is invalid."
               ;;
        esac
done
}

#-----------------------------------------------------------------------------
function prompt_value {
#
# Prompts the user for a value and present a default,
# in case the user press ENTER set variable RESULT to
# the default value.
#
go_on=""
prompt_msg="$1"
def_value="$2"

if [ ! "$prompt_msg" ]
then
	prompt_msg="Enter value"
fi

while [ ! "$go_on" ]
do
	printf "%s [%s] ?"  "$prompt_msg" "$def_value"
	read value
        case "$value" in
        	"") RESULT=$def_value
                	go_on=go
                ;;
                *) RESULT=$value
                	go_on=go
                ;;
        esac
done

}


#-----------------------------------------------------------------------------
function find_param_file {
#
# Look in the current directory for a file named <hostname>.parameters.
# If found return its name, if not, let the user to choose one.
#

	com_get_system_name

	if [ ! "$PARAMETER_FILE_NAME" ]
	then 
		PARAMETER_FILE_NAME=/tmp/${SYSTEM_NAME}.parameters
	fi

	if [ ! -f "$PARAMETER_FILE_NAME" ]
	then
            echo "No parameter file was found on default directory (${PARAMETER_FILE_NAME})."
            GO=""
	        while [ ! "$GO" ]
	        do 
                prompt_value "Please enter the name and path to the parameters file.\nType ENTER for none:"
                if [ ! "$RESULT" ]
		        then
                    echo "No parameters file used."
		        	PARAMETER_FILE_NAME="NONE"
                    GO=YES
		        else
		        	if [ -f ${RESULT} ]
                        then
                            PARAMETER_FILE_NAME=${RESULT}
	                        GO=YES
		                else
                            echo "The file ${RESULT} does not exist!"
	                    fi
	                fi
	        done
	else
		echo "Using $PARAMETER_FILE_NAME as input parameters file."
	fi
}


#-----------------------------------------------------------------------------
# Scans the parameter file for the supported keywords
#
# Receives
# Arg 1: The param file path/name
# Arg 2: The keyword to be found
#
# Returns
# The sequence os values for that directive
#
function parse_param_file_keyword {
#
# Receives a file name and scans it to set the internal 
# variables according to the directives found.

PARAM_FILE="$1"
KEYWORD="$2"

typeset -i idir=0
typeset -i idepot=0

cat $PARAM_FILE | awk -v keyword=$KEYWORD ' { if ($1 == keyword) { printf ("%s ", $2) } } ' 
        

}

#-----------------------------------------------------------------------------
# Verify if given host is accessible via ssh without password.
#
# Receives
# Arg 1: The host/IP
#
# Returns
# 0 if ok
# 1 otherwise
#
function check_ssh_connectivity {

	test_host=$1
	SSH_OK=1

	ssh -l root -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=1 \
		$test_host "echo test" > /dev/null 2>&1 && { SSH_OK=0 ; }
	
	return $SSH_OK
}

#-----------------------------------------------------------------------------
# Try to configure host based authentication to access 
# host via ssh without password.
#
# Receives
# Arg 1: The host/IP
#
# Returns
# 0 if ok
# 1 otherwise
#
function set_ssh_connectivity {

	test_host=$1

	./secsetup -r -k dsa $test_host || { return 1 ; } 

	return 0

}

#-----------------------------------------------------------------------------




