#!/usr/bin/ksh
#
# P2Vassist.sh
#
# Manages a physical to virtual migration.
#
# This script runs on the server that will host the virtual machine.
# It executes the necessary scripts remotely to gather information
# on the source host.
#
# Author: Alexandre W. Agostini
# Version: 1.0.0
# Date: 2006-08-30
#
# Version: 1.3.0
# Date: 2006-10-26
#
# (C) Copyright 2007 Hewlett-Packard Development Company, L.P.
#

trap "" int

#---------------------------------------------------------------------------+
# Load useful functions

INC_PATH=/opt/hpvm/bin
. $INC_PATH/p2vcommon



#---------------------------------------------------------------------------+
# $1 - remote dir to be created (full path)
# $2 - target host
#
# Nothing is done if dir already exists and is a directory.
# If dir is a file, returns an error.
function makeRemoteDir {
    typeset dirPath=$1
    typeset hostname=$2

    ssh -l root -o BatchMode=yes $hostname [[ -d $dirPath ]] && DIR_EXIST=1
    
    if [ ! "$DIR_EXIST" ]
    then
        echo DIR_NOT_EXISTS
        ssh -l root -o BatchMode=yes $hostname \
            "mkdir $dirPath" || { printf "ERROR!\n Could not create remote temporary directory!"; return 1 ; }
    fi    
    return 0    
}

#---------------------------------------------------------------------------+
# $1 - [Source host:]file
# $2 - [Target host:]file 
function transferFile {
    typeset sourcePath=$1
    typeset targetPath=$2

    scp -q $sourcePath $targetPath || { printf "ERROR!\n Could not transfer file to/from the remote host!"; return 1 ; }
    
    return 0
}

#---------------------------------------------------------------------------+
# $1 - IP address of host to be resolved
function getHostnameFromIP {
    typeset ip_host=$1
    
    HOSTNAME=`ssh -l root -o BatchMode=yes $ip_host hostname` || return 1
}


#---------------------------------------------------------------------------+
function get_server_hostname {

	msg=$1
	OUT_VAR=$2

	IP_ADDRESS=NO
	
    printf "%s\n" $msg
    read HOSTNAME
	
    if [ "$HOSTNAME" ]
    then
        echo $HOSTNAME | grep -q -E "^[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}$" && IP_ADDRESS=YES
        if [ "$IP_ADDRESS" = YES ]
        then
            isValidIP $HOSTNAME || { printf "IP address $HOSTNAME is not valid.\n" ; return 1 ; }
        fi
		
		#check_ssh_connectivity $HOSTNAME || { set_ssh_connectivity $HOSTNAME || { printf "Could not set ssh connectivity to $HOSTNAME, please check network parameters.\n" ; return 1 ; } ; }

        HOSTNAME=$(getHostnameFromIP $HOSTNAME) || return 1
			
        typeset $OUT_VAR=$HOSTNAME
	else
		return 1
    fi
}


#---------------------------------------------------------------------------+
function getSourceHostname {
    printf "Type the hostname or IP address of \nthe source host to be migrated (<Enter> skips):\n"
    read HOSTNAME
    if [ "$HOSTNAME" ]
    then
        echo $HOSTNAME | grep -q -E "^[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}$" && IP_ADDRESS=$HOSTNAME
        if [ "$IP_ADDRESS" ]
        then
            isValidIP $IP_ADDRESS || { printf "IP address $IP_ADDRESS is not valid.\n" ; return 1 ; }
			check_ssh_connectivity $IP_ADDRESS || { 
													set_ssh_connectivity $IP_ADDRESS || { printf "Could not set ssh connectivity to $IP_ADDRESS, please check network parameters.\n" ; return 1 ; }
												}
            getHostnameFromIP $IP_ADDRESS || return 1
        fi
        SOURCE_HOST=$HOSTNAME
    fi
}


#---------------------------------------------------------------------------+
function getTargetHostname {
    printf "Type the hostname or IP address of the target virtual machine or \nphysical server that will receive the application:\n"
    read HOSTNAME
    if [ "$HOSTNAME" ]
    then
        echo $HOSTNAME | grep -q -E "^[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}$" && IP_ADDRESS=$HOSTNAME
        if [ "$IP_ADDRESS" ]
        then
            isValidIP $IP_ADDRESS || { printf "IP address $IP_ADDRESS is not valid.\n" ; return 1 ; }        
            getHostnameFromIP $IP_ADDRESS || return 1
        fi
        TARGET_HOST=$HOSTNAME
    fi
}


#---------------------------------------------------------------------------+
function analyseSourceHost {
	
	check_ssh_connectivity $SOURCE_HOST || {  set_ssh_connectivity $SOURCE_HOST || { printf "Error: couldn't set ssh access to the server.\n" return 1  ; } ; }

    makeRemoteDir $REMOTE_TEMP_DIR $SOURCE_HOST 						|| { return 1 ; }
    transferFile $UTILITIES_SCRIPT_NAME $SOURCE_HOST':'$REMOTE_TEMP_DIR || { return 1 ; }
    transferFile $ANALYZE_SCRIPT_NAME $SOURCE_HOST':'$REMOTE_TEMP_DIR 	|| { return 1 ; }
	
	PHYS_INFO=0
	PARM_INFO=0
	

	ssh -l root -o BatchMode=yes $SOURCE_HOST \
			"cd $REMOTE_TEMP_DIR; ./analyzesys $TERM P2VAPP" && { PHYS_INFO=1 ; }

    if [ $PHYS_INFO = 1 ]
    then
        resultFile=$SOURCE_HOST'.'$ANALYZE_RESULT_SUFFIX		
        transferFile $SOURCE_HOST':'$REMOTE_TEMP_DIR'/'$resultFile ./ || { return 1 ; }
        return 0
    fi
	
    # if [ $PARM_INFO = 1 ]
    # then
        # resultFile=$SOURCE_HOST'.'$PARAM_RESULT_SUFFIX
        # transferFile $SOURCE_HOST':'$REMOTE_TEMP_DIR'/'$resultFile ./ || { return 1 ; }
        # return 0
    # fi
}

#---------------------------------------------------------------------------+
function createVirtualMachine {
    printHeader "Creating virtual machine"
    
    ./createvm
}

#---------------------------------------------------------------------------+
function AnalyzeRemoteSystem {

	printHeader "Analyzing Host $PHYSICAL_HOSTNAME"
	analyseSourceHost $PHYSICAL_HOSTNAME || { printf "\nAnalysis Phase of $HOSTNAME failed.\n"; return 1 ; }
	return 0
}

#-----------------------------------------------------------------------------
# Create VM on defined host with informed hardware parameters
function Create_Virtual_Machine {
	
	if [ "$vm_host" ]
	then
		printf "\nGenerating hpvmcreate command line...\r"
		check_ssh_connectivity $vm_host || { set_ssh_connectivity $vm_host || { printf "Error: couldn't set ssh access to the VM Host.\n" return 1  ; } ; }

	    makeRemoteDir $REMOTE_TEMP_DIR $vm_host 						  || { return 1 ; }
	    transferFile createvm  $vm_host':'$REMOTE_TEMP_DIR || { return 1 ; }
		transferFile $UTILITIES_SCRIPT_NAME   $vm_host':'$REMOTE_TEMP_DIR || { return 1 ; }
	    transferFile $PHYSICAL_INFO_FILE_NAME $vm_host':'$REMOTE_TEMP_DIR || { return 1 ; }
	
		# Generate vm creation cmd file
		ssh -l root -o BatchMode=yes $vm_host \
			"cd $REMOTE_TEMP_DIR; ./createvm $vm_host $PHYSICAL_INFO_FILE_NAME $target_host" && { return 0 ; }
		
		return 1
	else
		printf "Virtual machine creation option set but no VM host defined.\n"
		return 1
	fi
}

#-----------------------------------------------------------------------------
# Read the VM creation parameter file for an IP boot address.
# Use the first address defined there.
# Return an error status if could not find one.
function get_boot_ip_address {

let i=0

cat $PHYSICAL_INFO_FILE_NAME | grep -v -E ' *#|N/A' | grep -E "^NET " |
	while read type lan_dev ip status
        do
        	arr_lan[$i]=$lan_dev
                arr_ip[$i]=$ip
        	let i=$i+1
        done

	if [ i = 0 ]
	then
		return 1
	else
		BOOT_IP_ADDRESS=${arr_ip[0]}
		return 0
	fi
}

#-----------------------------------------------------------------------------
# Check if the IP answer to ping.
# This IP should not be in use for the virtual machine be able to boot.
function check_boot_ip_address {

	ping $BOOT_IP_ADDRESS -n 1 > /dev/null 2>&1 && { return 1 ; }
	return 0

}

#-----------------------------------------------------------------------------
# Initiates an HP-UX instalation on the VM created in the host
#
# Uses targetvm
#      iuxserver
#      
function Deploy_VirtualMachine_OS { 
	
	check_ssh_connectivity $IUX_array || { set_ssh_connectivity $IUX_array || { printf "Error: couldn't set ssh access to the IgniteUX server.\n" return 1  ; } ; }

	mac_addr=$(ssh -l root -o BatchMode=yes $vm_host "/opt/hpvm/bin/hpvmstatus -P $target_host | grep 'vswitch   lan' | awk '{ print \$8 }' | tr -d '-'")
	
	ssh -l root -o BatchMode=yes $IUX_array "echo $STD_BOOT_TEMPLATE >> /etc/bootptab"
	
	get_boot_ip_address || { printf "Error: couldn't set boot ip address.\n"; return 1  ; }
	
	check_boot_ip_address || { printf "Error: boot ip address %s is already in use.\n" $BOOT_IP_ADDRESS ; return 1  ; }
	
	printf "$GUESTBOOTPARMS" $target_host $BOOT_IP_ADDRESS $mac_addr | read guest_line
	
	ssh -l root -o BatchMode=yes $IUX_array "echo $guest_line >> /etc/bootptab"
	
	ssh -l root -o BatchMode=yes $vm_host "/opt/hpvm/bin/hpvmstart -P $target_host > /dev/null 2>&1" || { printf "Failed to start Guest.\n"; return 1 ; }

	printf "Waiting Virtual Machine %s to start " $target_host
	while true
	do
		sleep 10
		VM_STATUS=$(ssh -l root -o BatchMode=yes $vm_host "/opt/hpvm/bin/hpvmstatus -V -P $target_host | grep 'State' | awk '{ print \$3,\$4 }'")
		if [ "$VM_STATUS" = 'On (EFI)' ]
		then
			break
		fi
		printf "."		
	done
	printf "\nVirtual machine sucessfully started.\n\n"
	
	printf "------------------ [ Important Note ] -------------------- \n\n"
	printf " The Operational System is about to be installed in the    \n"
	printf " %s VM, through an hpvmconsole access to it and this       \n" $target_host
	printf " process may take a long time to finish. Please remember   \n"
	printf " to exit from the console (type ctrl-B) when the           \n"
	printf " instalation finishes (the VM will be rebooted) to allow   \n"
	printf " the migration to continue.                                \n\n"
	printf " Press <Enter> to continue                                 \n"
	printf "---------------------------------------------------------- \n"
	printf "---> "
	read dummy
		
	printf "\nInitiating O.S. instalation...\n"
	
	ssh -l root -tt -o BatchMode=yes $vm_host \
		"( printf 'co\n'; sleep 1; printf 'cls\015'; sleep 1; printf 'lanboot select\015 01\015'; sleep 10; printf '\002' ) | /opt/hpvm/bin/hpvmconsole -P $target_host -Fi " || \
		{ printf "Failed to start install on guest.\n"; return 1 ; }
	ssh -l root -tt -o BatchMode=yes $vm_host "/opt/hpvm/bin/hpvmconsole -P $target_host -c 'co -nc' -i" || { printf "Failed to start install on guest.\n"; return 1 ; }

	ping $target_host -n 10 > /dev/null 2>&1 || { 
			printf "------------------ [ Atention ] -------------------- \n\n"
			printf " The virtual machine %s could not be contacted.      \n\n" $target_host
			printf " Please check the instalation process.               \n" 
			printf "---------------------------------------------------- \n"
			printf "\n"
			printf "\n"
			return 1 
		}

	return 0
}

#-----------------------------------------------------------------------------
function Analyze_Remote_Application {

	if [  ! "$PARAMETER_FILE_NAME" ]
	then
		find_param_file
        if [ "$PARAMETER_FILE_NAME" = "NONE" ]
        then
			printf "Input parameters file not defined. Cannot proceed.\n"
			exit 1
        fi
	fi
	
	if [ "$install_array" -a "$depots_array" ]
	then
		printf "Error: the <installscript> and the <swcomponent> directives are mutually exclusive.\n"
		exit 1
	fi

	if [ ! "$source_host" ]
	then
		LOCAL_HOST=$(hostname)
		printf "Source server not defined. Assuming local host: $LOCAL_HOST.\n"
		SOURCE_HOST=$LOCAL_HOST
	else
		SOURCE_HOST=$source_host
	fi
	
	check_ssh_connectivity $SOURCE_HOST || { set_ssh_connectivity $SOURCE_HOST || { printf "Could not set ssh connectivity to $SOURCE_HOST, please check network parameters.\n" ; return 1 ; } ; }
	
	if [ ! "$target_host" ]
	then
		printf "Target server not defined.\n"
		exit 1 
	else
		TARGET_HOST=$target_host
	fi
	
	check_ssh_connectivity $TARGET_HOST || { set_ssh_connectivity $TARGET_HOST || { printf "Could not set ssh connectivity to $TARGET_HOST, please check network parameters.\n" ; return 1 ; } ; }

	return 0
}

#-----------------------------------------------------------------------------
function Check_OS_Versions {

	SourceOS=`ssh -l root -o BatchMode=yes $TARGET_HOST "uname -r"`
	TargetOS=`ssh -l root -o BatchMode=yes $SOURCE_HOST "uname -r"`
	
	if [ "$SourceOS" != "$TargetOS" ]
	then
		return 1
	else
		return 0
	fi
}

#-----------------------------------------------------------------------------
# Sets variable APP_INSTALLED if app. already on target system.
# Returns not zero if something awful happened ;-)
function Check_Application_Installed {

	APP_INSTALLED=1
	
	if [ "$install_array" ]
	then
		APP_INSTALLED=0
		return 0
	fi
	
	SWLIST_TEMP_FILE=/tmp/$TARGET_HOST.swlist

	ssh -l root -o BatchMode=yes $TARGET_HOST "swlist -l product" > $SWLIST_TEMP_FILE || { return 1 ; }

	for d in ${depots_array[@]}
	do
		grep -q $d $SWLIST_TEMP_FILE
		if [ $? != 0 ]
		then
			APP_INSTALLED=0
		fi
	done
	
	rm $SWLIST_TEMP_FILE
	return 0
}


#-----------------------------------------------------------------------------
# Try to stop the application by calling any shutdown scripts that may exist
# on the target host.
function Stop_Application {

	SHUTDOWN_OK=YES
	
	if [ "$install_array" ]
	then
		printf "\n\n"
		printf "------------------ [ Atention ] -------------------- \n\n"
		printf " Since the instalation process was executed by an    \n"		
		printf " external program, P2VAssistant cannot automatically \n"		
		printf " stop it.                                            \n"				
		printf " You should now stop the application (case it was    \n" 
		printf " automatically started) to let transferring of       \n"
		printf " application data to occur.                          \n\n"
		printf " Please press <Enter> when ready.                    \n\n"
		printf "---------------------------------------------------- \n"
		printf "--> "
		read dummy
		return 0
	else
		printf "Trying to stop application installed on target server...\n"
		for d in ${depots_array[@]}
		do

			ssh -l root -o BatchMode=yes $SOURCE_HOST "swlist -l file $d | grep '/sbin/init.d' | cut -d: -f2" | \
				while read shutdown_script
				do
					echo "\tCalling $shutdown_script on $TARGET_HOST ..."
					ssh -l root -o BatchMode=yes $TARGET_HOST "$shutdown_script stop" || { SHUTDOWN_OK=NO ; }
				done
		done
		if [ $SHUTDOWN_OK=YES ]
		then
			return 0
		else
			return 1
		fi
	fi
}

function Get_Depot_Version {
    depot_name=$1;
    target_host=$2;
    depot_server=$3;
    if [ "x$depot_server" = x ]
    then
        #printf "`swlist -l product $depot_name @$target_host | grep $depot_name | grep -v -E "^#" | awk '{print $2}'`\n"
        printf "`ssh -l root -o BatchMode=yes $target_host \"swlist -l product $depot_name\" | grep $depot_name | grep -v -E "^#" | awk '{print $2}'`\n"
    else
        printf "`swlist -l product -s $depot_server $depot_name | grep $depot_name | grep -v -E "^#" | awk '{print $2}'`\n"
    fi
}

#-----------------------------------------------------------------------------
# Try to install the application from the supplied IgniteUX server.
# Aborts if no Ignite server found or could not contact it.
function Install_Application {

	if [ ! "$install_array" ]
	then
		for SDserver in ${SD_array[@]}
		do
            already_installed=NO
            installed_sw=
			target_sw_list=`ssh -l root -o BatchMode=yes $TARGET_HOST "swlist -l product 2>/dev/null"`
            for dep in ${depots_array[@]}
            do
                #ssh -l root -o BatchMode=yes $TARGET_HOST "swlist -l product $dep > /dev/null 2>&1"
				echo $target_sw_list | grep -q -i $dep
                if [ $? = 0 ]
                then
                    already_installed=YES
                    app_version_target=`Get_Depot_Version $dep $TARGET_HOST`
                    app_version_repository=`Get_Depot_Version $dep $TARGET_HOST $SDserver`
                    installed_sw="$installed_sw\t  $dep - $app_version_target - $app_version_repository\n";
                fi

            done
            if [ $already_installed = YES ]
            then
                printf "\t---------------------- [ Atention ] ----------------------\n\n"
                printf "\t  One or more of selected application (s) are already \n"
                printf "\t  installed on target system $TARGET_HOST. \n" 
				printf "\t  The applications are listed below\n\n "
                printf "\t  Application - Target Version - Repository Version\n"
                printf "$installed_sw\n"
				
                printf "\t  It's strongly recommended to stop that all applications \n"
				printf "\t  listed above (or any other using them) before continuing \n "
				printf "\t  with the installation.\n\n"
                printf "\t  All selected applications already installed on target \n"
				printf "\t  host will be removed. Notice that any patchs and/or other \n"
				printf "\t  updates may be lost if older versions are installed.\n\n"
                printf "\t  Type <yes> below if you would like to continue\n"
                printf "\t----------------------------------------------------------\n"
                choice=NO
                printf "\t--> "
                read choice
                if [ "$choice" = 'yes' ]
                then
            		printf "\n\t  Removing depots..."
                    ssh -l root -o BatchMode=yes $TARGET_HOST "swremove ${depots_array[*]}" > /dev/null 2>&1
					printf "done.\n"

            		printf "\n\t  Installing depots..."
					ssh -l root -o BatchMode=yes $TARGET_HOST "swinstall -x autoreboot=true -x mount_all_filesystems=false -s $SDserver ${depots_array[*]}" > /dev/null 2>&1 && { printf "done.\n"; return 0 ; }
					#printf "done.\n"
                fi
			else
            	printf "\n\t  Installing depots..."
				ssh -l root -o BatchMode=yes $TARGET_HOST "swinstall -x autoreboot=true -x mount_all_filesystems=false -s $SDserver ${depots_array[*]}" > /dev/null 2>&1 && { printf "done.\n"; return 0 ; }
			fi
		done
	else
		SOME_FAILED=0
		printf "Please press <Enter> to continue with the instalation, or\n"
		printf "type 's' to skip the execution on the scripts:\n"
		printf "---> "
		typeset -l dummy
		read dummy
		
		if [ "$dummy" = 's' ]
		then
			printf "\nInstall scripts execution skipped.\n"
		else
			for install_script in ${install_array[@]}
			do
				printf "\n\nPreparing to run install script %s on %s ...\n" "$install_script" $TARGET_HOST
				printf "Please press <Enter> when ready: "
				read dummy
				ssh -l root -o BatchMode=yes $TARGET_HOST "$install_script" || { SOME_FAILED=1 ; }
			done
		fi
	fi
	
	[[ $SOME_FAILED = 0 ]] && { return 0 ; }

	printf "\n\n"
	printf "\t---------------------- [ Atention ] ----------------------\n\n"
	printf "\t  The instalation procedure appears to have failed but it \n"
	printf "\t  is still possible to go on and transfer the application \n"
	printf "\t  data anyway.\n\n"
	printf "\t  If you choose to continue to transfer the application  \n"
	printf "\t  contents type <yes> bellow, any other option aborts.\n"
	printf "\t----------------------------------------------------------\n"
	choice=NO
	printf "\t--> "
	read choice
	if [ "$choice" = 'yes' ]
	then
		return 0
	fi
	#exit 1
	return 1
}


#-----------------------------------------------------------------------------
# 
function Check_Patch_Level {
	
	printf "\n\n"
	printf "---------------------- [ Atention ] ----------------------\n"
	printf "  You may now install the patches required by the         \n"
	printf "  application (if any).                                   \n\n"
	printf "  Please press <Enter> to continue migration process.      \n"
	printf "----------------------------------------------------------\n"
	printf "--> "
	read dummy
	
	return 0
}


#-----------------------------------------------------------------------------
#
function Copy_Application_Files {
	
	printf "\tChecking application disk space...\n"
	Check_Application_Space || { printf "Not enough free space on target server to transfer dir/files\n" ; return 1 ; }

	for dir in ${dirs_array[@]}
	do
		printf "\tTransferring $dir directory to $TARGET_HOST, please wait...\n"
		tar cf - $dir 2> /dev/null | ssh -l root -o BatchMode=yes $TARGET_HOST "tar xf - " 2> /dev/null || { return 1 ; }
	done

	for afile in ${files_array[@]}
	do
		printf "\tTransferring the file $afile to $TARGET_HOST, please wait...\n"
		transferFile $SOURCE_HOST':'$afile  $TARGET_HOST':'$afile  || { return 1 ; }
	done

	for adisk in ${disks_array[@]}
	do
		printf "\tTransferring the contents of raw device $adisk to $TARGET_HOST, please wait...\n"
		dd if=$adisk cbs=1024 | ssh -l root -o BatchMode=yes $TARGET_HOST "dd of=$adisk cbs=1024" || { return 1 ; }
	done	
	
	return 0
}

#-----------------------------------------------------------------------------
# 
function Check_Application_Space {
	
	for dir in ${dirs_array[@]}
	do
		target_mount_point=`Get_Object_MountPoint $TARGET_HOST $dir` || { printf "Error analyzing disk space (mount).\n"; return 1 ; }
		target_free_space=`Get_MountPoint_FreeSpace $TARGET_HOST $target_mount_point` || { printf "Error analyzing disk space (free).\n"; return 1 ; }
		source_space_used=`Get_Object_SpaceUsed $SOURCE_HOST $dir`  || { printf "Error analyzing disk space(used).\n"; return 1 ; }
		
		printf "%s %s %s\n" $target_mount_point $target_free_space $source_space_used
	done | awk '    { mount=$1; free=$2; used=$3; 
					#	printf ("...mount=%s free=%s used=%s\n", mount, free, used)  
						if (! $1 in total_used) {
							total_used[mount]=0 
					#		printf ("%s init-total: %d\n", mount, total_used[mount])
						}
						total_free[mount] = free
						total_used[mount] = total_used[mount] + used 
					#	printf ("sub-total: %d\n", total_used[mount])
					} 	
				END { for (m in total_used) 
						printf ("mount %s needed %d free %d\n", m, total_used[m], total_free[m]) 
					} ' | while read s1 mount s2 needed s3 free
							do
								if [ $needed -gt $free ]
								then
									printf "Not enough space on %s (%d KB) to copy application files (%d KB).\n" $mount $free $needed 
									return 1
								fi
							done
	return 0
}


#-----------------------------------------------------------------------------
# Receives a server and a file or directory and returns its mount 
# point on that particular server.
#
# It determines the mount by searching in the output of "df"  for 
# the exact name, if not found, go up one level and try again.
#
# Not a very eficient algorithm but works for now ;-)
#
function Get_Object_MountPoint {

    server=$1
	dir_test=$2
    found=NO
    while [ "$found" != YES ]
    do
		ssh -l root -o BatchMode=yes $server "fuser -c $dir_test > /dev/null 2>&1"
        if [ $? != 0 ]
        then
        	if [ $dir_test = "/" ] #New stop condition
            then
                echo "/"
                exit 1
            fi
        	
			dir_test=`dirname $dir_test`
        else
        	echo $dir_test
            return 0
        fi
    done
	if [ $found = NO ]
	then
		echo "/"
		return 1
	fi
}


#-----------------------------------------------------------------------------
#
function Get_MountPoint_FreeSpace {

	server=$1
	mount_point=$2
    
	ssh -l root -o BatchMode=yes $server "df -b $mount_point | cut -d: -f2 | awk '{ print \$1 }'"
}


#-----------------------------------------------------------------------------
#
function Get_Object_SpaceUsed {

	server=$1
	object_path=$2

	du -sk $object_path | awk '{ print $1 }'
}


#-----------------------------------------------------------------------------
#
function parse_options {

	CREATE_VM=NO
	CHECK_PATCH_LEVEL=NO
	P2V_APP=NO
	ANALYZE_SYSTEM=NO

    # Run through the menu options
	while getopts "f:c:a:" OPT 
	do
		case $OPT in
			f)
				PARAMETER_FILE_NAME=$OPTARG
				[[ -r $PARAMETER_FILE_NAME ]] || {	printf "Unable to read input parameter file %s\n" "$PARAMETER_FILE_NAME"
													exit $FAILURE ; }
				P2V_APP=YES
				
				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`
				
				printf "Using input parameter file: %s\n" "$PARAMETER_FILE_NAME"
            ;;

			c) 	if [ "$P2V_APP" = YES ]
				then
					PHYSICAL_INFO_FILE_NAME=$OPTARG
					[[ -r $PHYSICAL_INFO_FILE_NAME ]] || {	printf "Unable to read physical info parameter file %s\n" "$PHYSICAL_INFO_FILE_NAME"
															exit $FAILURE ; }
					CREATE_VM=YES
					printf "\nAutomatic creation of virtual machine\n" 
					printf "   VM host: %s\n" $vm_host
					printf "   VM name: %s\n" $target_host
					printf "   Physical info file: %s \n" $PHYSICAL_INFO_FILE_NAME
				else
					printf "Invalid option without -f specified.\n"
					exit $FAILURE
				fi
            ;;
			
			a) 	if [ "$P2V_APP" = YES ]
				then
					printf "Options -f and -a are mutually exclusive.\n"
					exit $FAILURE
				else
					ANALYZE_SYSTEM=YES
					PHYSICAL_HOSTNAME=$OPTARG
					SOURCE_HOST="$PHYSICAL_HOSTNAME"
				fi
            ;;

			*)
				printf "invalid option: %s\n" "$OPTARG"
				Usage $@
				exit 1
            ;;
		esac
	done
	shift $OPTIND-1
		
	if [ ! "$P2V_APP" -a ! "$ANALYZE_SYSTEM" ]
	then
		printf "No option used.\n"
		Usage
		exit $FAILURE		
	fi
}

#-----------------------------------------------------------------------------
#
#
function Usage {
   echo "
usage: p2vassist {-f param_file [-c physical_param_file] | -a hostname}

   -f param_file  : Specifies a file containing the list of parameters.
   
   -a hostname    : Create a file describing the hardware of the 
					informed hostname/IP. 
   
   -c param_file  : Specifies a file describing the atributes for the
					VM to be created. You may create an initial physical
					info file executing p2vassist -a hostname.

"
  exit $FAILURE
}

#-----------------------------------------------------------------------------
#
#
function Main 
{

	printHeader

	parse_options $@	
	
	if [ $ANALYZE_SYSTEM = YES ]
	then
		AnalyzeRemoteSystem 
		if [ $? = 0 ]
		then
			printf "Source Analyzing Succeeded.\n\n"
			cwd=`pwd`
			printf "Result file is $cwd/$PHYSICAL_HOSTNAME.phys_info.\n\n"
			exit 0
		else	
			printf "Source Analyzing Failed.\n\n"
			exit 1
		fi
	fi
	
	if [ $CREATE_VM = YES ]
	then
		Create_Virtual_Machine
		if [ $? = 0 ]
		then
			printf "Virtual machine created successfully.\n\n"			
			Deploy_VirtualMachine_OS $vm_host $target_host
			if [ $? = 0 ]
			then
				printf "O.S. successfully installed on virtual machine.\n\n"
			else
				printf "O.S. instalation on virtual machine failed.\n\n"
				exit 1
			fi
		else
			printf "Virtual machine creation failed.\n\n"
			exit 1
		fi
	fi

	printHeader " P2V Applications "
	
	Analyze_Remote_Application
	if [ $? = 0 ]
	then
		printf "Source Analyzing Succeeded.\n\n"
	else
		printf "Source Analyzing Failed.\n\n"
		exit 1
	fi

	Check_OS_Versions
	if [ $? = 0 ]
	then
		printf "Source and Target O.S. Versions Match.\n\n"
	else
		printf "Source and Target O.S. Versions Do not Match.\n\n"
		exit 1
	fi

	Check_Application_Installed
	if [ $? != 0 ]
	then
		printf "Application Instalation check Failed.\n\n"
		exit 1
	fi
	
	if [ $APP_INSTALLED = 0 ]
	then
		printf "Application not installed on target server [$TARGET_SERVER], proceeding to installation...\n\n"
		Install_Application
		if [ $? = 0 ]
		then
			printf "Application Successfully Installed.\n\n"
		else
			printf "Application Installation Failed.\n\n"
			exit 1
		fi			
	fi
	
	Stop_Application
	if [ $? = 0 ]
	then
		printf "Application Successfully Stopped.\n\n"
	else
		printf "Application Stop Failed. Maybe application was not running.\n\n"
	fi

	Check_Patch_Level
	
	Copy_Application_Files
	if [ $? = 0 ]
	then
		printf "\nApplication Migration Succeeded.\n\n"			
	else
		printf "\nApplication Migration Failed.\n\n"
		exit 1
	fi

	exit 0
}

#  /-------------------------------------------------------------------------\
# |	                           Main Procedure                                 |
#  \-------------------------------------------------------------------------/


check_root_user

MainMenu

exit

if [ $# = 0 ]
then	
	Usage
	exit 1
fi
	

Main $@


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