#!/usr/bin/ksh
#
# CreateVirtualMachine.sh
#
# Generate a script with the hpvmcreate command based on the input
# file content.
#
# The input file was created by the AnalyzeSystemResources.sh and will 
# be named <hostname>.phys_info
#
# Upon execution the script looks in the current directory for files 
# with extension .phys_info and let the user to choose between them.
#
# The output script will have a name of the form:
#
# vm<original hostname>.sh
#
#
# Author: Alexandre W. Agostini
# Version: 1.0.0
# Date: 2006-08-14
#
# Version: 1.3.0
# Date: 2006-10-26
#
# (C) Copyright 2007 Hewlett-Packard Development Company, L.P. 
#



# Load useful functions
INC_PATH=/opt/hpvm/bin
. $INC_PATH/p2vcommon


#-----------------------------------------------------------------------------
function init_out_file {
	echo "# "
    echo "# ------------------------------------------"
	echo "#  Virtual Machine Creation Script"
	echo "# ------------------------------------------"
	echo "# "
    echo "# "
	echo "# Created on "`date`
    echo "# "
}

#-----------------------------------------------------------------------------
function get_files_list {
	let i=0
	for disk_file in `ls *.phys_info`
    do
        	host_name=`echo $disk_file | cut -d. -f1`
            lista_arquivos[$i]=$host_name
            let i=$i+1
    done
    if [ $i -eq 0 ]; then
        echo "No configuration files (*.phys_info) found in current directory."
        exit 1
    fi
        
	echo
        echo "Configuration files found in current directory"
	echo
        printf "%s   %-10s\n\n" Option Hostname 
        let i=0        
        for name in ${lista_arquivos[*]}
        do
        	printf "[ %2d ] - %-10s\n"  $i ${name}
                let i=$i+1
        done
        printf "\nPlease choose a number (ENTER exits):"
        read option
        
        if [ ! "$option" ]
        then
        	echo "No option selected, exiting.\n\n" 
        	exit
        else
        	NUM_OK=0
        	echo $option | grep -q -E "^[0-9]+$" && NUM_OK=1
                if [ $NUM_OK = 1 ]
                then
                	if [ ! "${lista_arquivos[$option]}" ]
                        then
                        	echo "Option - $option not found"
                            echo "Returning to previous menu"
                            sleep 1
                            exit
                        else
                        	HOST_CHOSEN="${lista_arquivos[$option]}"
                        fi
                else
                	echo "Invalid option - $option"
                    echo "Returning to previous menu"
                    sleep 1
                    exit
                fi
        fi

}
#-----------------------------------------------------------------------------
# Prints the information from the network part of the config. file hostname.phys_info
function print_source_net {
        echo "Network cards on host: $1"
        cat $1.phys_info | awk ' ! / *#/ { if ($1 == "NET" && $4 == "UP") { print $0 } }'
        echo "\n"
}

#-----------------------------------------------------------------------------
# Prints the information from the disk config. part of the file hostname.phys_info
function print_source_disk {
	echo "Disk volumes on host: $1"
	cat $1.phys_info | awk ' ! / *#/ { if ($1 == "DSK") { print $0 } }'
    echo "\n"
}

#-----------------------------------------------------------------------------
# Input: hostname portion of config. file
function map_disk {
    #printHeader "Mapping Physical Disk Volumes"

    let i=0
    cat $1.phys_info | grep -v -E ' *#' | grep -E "^(DSK|LV|FILE) " |
        while read type dsk_dev size
        do
			arr_type[$i]=$type
            arr_disk[$i]=$dsk_dev
            arr_size[$i]=$size
            let i=$i+1
        done

    let i=0
    for dsk in ${arr_disk[*]}
    do
        #printf "Where do you want to map %s (%d MB)?\n" $dsk ${arr_size[$i]}
        get_disk_map_option $i $dsk ${arr_type[$i]}
        let i=$i+1
    done
}

#-----------------------------------------------------------------------------
function get_disk_map_option {
index=$1
device_id=$2
dev_type=$3

GO=""
while [ ! "$GO" ]
do
	#echo "Backing device type (DVD, DISK, LVOL, FILE)?"
	#read bdtype
	bdtype=$dev_type

	case $bdtype in
		DVD) 	example="/dev/rdsk/c0t0d0"
	        	virtual_type=dvd
                host_type=disk
	            GO=YES
	        ;;
		DSK) 	example="/dev/rdsk/c2t0d0"
	        	virtual_type=disk
                host_type=disk
	            GO=YES
	        ;;
	    LV) 	example="/dev/vg00/rlvol1"
                virtual_type=disk
                host_type=lv
	            GO=YES
	        ;;
		FILE) 	example="/var/adm/virtual.dsk"
	        	virtual_type=disk
                host_type=file
	            GO=YES
	        ;;
	    *) echo "option $dmp not recognized"
	        ;;
	esac
done

#echo "Device id (ex. $example)?"
#read dev_id
dev_id=$device_id


DISK_DEV[$index]=`printf "%s:scsi::%s:%s" ${virtual_type} ${host_type} ${dev_id}`
if [ $host_type = "file" ]
then
    DISK_DEV_FILE_ALLOC[$index]=${dev_id}
fi

}

#-----------------------------------------------------------------------------
function get_vswitches {

#echo "\nVirtual Switches on $SYSTEM_NAME:\n"
#hpvmnet
echo 

}

#-----------------------------------------------------------------------------
# Input: hostname portion of config. file
function map_network {
#echo "Mapping Network card on virtual switches"

let i=0
cat $1.phys_info | 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

let i=0
for lan in ${arr_lan[*]}
do
    #printf "Do you want to map physical lan card $lan to a virtual switch in the VM?\n"
    #prompt_YesNo
    #if [ "$RESULT" = "YES" ]; then
        #printf "\nWhich vswitch to use for network %s ip: %s\n (choose from the above or type ENTER to create a new one)?" $lan ${arr_ip[$i]}
        get_net_map_option $i
        let i=$i+1
    #fi
done
}

#-----------------------------------------------------------------------------
# Input: index of the vswitch to be used
function get_net_map_option {
	
	index=$1

	/opt/hpvm/bin/hpvmnet | grep -vE "localnet|========|Name     Number State" | awk '{ print $1 }' | head -1 | read vswitch
	
	if [ "$vswitch" ]
	then
		#echo "Using $vswitch"
		VS_NAME[$index]=$vswitch
	else
		#echo "Type the name and the PPA number for the new \nvirtual switch, max. 8 chars (ex. vstest01 0):"
	    echo "vs01 0" | read vs_name ppa
	    VS_CREATION_CMD[$index]="$vs_name:$ppa"
	    VS_NAME[$index]=$vs_name
	fi
}

#-----------------------------------------------------------------------------
#disk:scsi:0,0,4:disk:/dev/rdsk/c2t2d1
#
#  ${DISK_DEV_FILE_ALLOC[*]}  ${arr_size[$i]}  => file_path file_size
#  ${VS_CREATION_CMD[*]}                       => vsname:nic_nr
#  ${VS_NAME[*]}								=> vsname
#  ${DISK_DEV[*]}								=> "%s:scsi::%s:%s" ${virtual_type} ${host_type} ${dev_id}
#
function create_vm_cmd {

BASE_CMD=/opt/hpvm/bin/hpvmcreate

CMD="$BASE_CMD -P $VM_NAME -O HPUX -l \"Host $HOST_CHOSEN consolidated\" "

#RSRC_LIST=`cat $1.phys_info | awk ' ! / *#/ { if ($1 == "DSK") { sub("/dsk/", "/rdsk/"); printf(" -a disk:scsi::disk:%s", $1 );} } '`

integer i=0
for dsfa in ${DISK_DEV_FILE_ALLOC[*]}
do
	printf "# Allocating virtual storage.\n" | tee -a $OUT_FILE
	printf "/opt/hpvm/bin/hpvmdevmgmt -S %dM %s || { echo \"Error allocating virtual disk \"; exit 1 ; }\n\n" ${arr_size[$i]} $dsfa | tee -a $OUT_FILE
    i=$i+1
done


for vscreate in ${VS_CREATION_CMD[*]}
do
	printf "# Creating virtual switch\n" | tee -a $OUT_FILE
    echo $vscreate | awk -F: ' { printf("/opt/hpvm/bin/hpvmnet -c -S %s -n %s\n\n", $1, $2) }' | tee -a $OUT_FILE
done


printf "%s " $CMD  | tee -a $OUT_FILE
[ "$CPU_percent" ] &&  printf "-e %s " $CPU_percent | tee -a $OUT_FILE
[ "$CPU_number"  ] &&  printf "-c %s " $CPU_number  | tee -a $OUT_FILE
[ "$MEM_size"    ] &&  printf "-r %s " $MEM_size    | tee -a $OUT_FILE


for vs in ${VS_NAME[*]}
do
	printf " \\"  | tee -a $OUT_FILE
    printf "\n"   | tee -a $OUT_FILE
	printf " -a network:lan::vswitch:%s " $vs | tee -a $OUT_FILE

done

for ds in ${DISK_DEV[*]}
do
	printf " \\"         | tee -a $OUT_FILE
	printf "\n"          | tee -a $OUT_FILE
	printf " -a %s " $ds | tee -a $OUT_FILE
done

printf "\n" | tee -a $OUT_FILE

#echo "\n\n"
#echo "This command was saved in the file: "`pwd`"/${OUT_FILE}"
# printf "VM configuration complete.\n" 
#`pwd`"/${OUT_FILE}"
# printf "Press <enter> to create the virtual machine.\n" 
# prompt_AnyKey
# `pwd`"/${OUT_FILE}"

}

#----------------------------------------------------------------------------
function MapSystemResources {

	#echo "\n\nUsing configuration files for host: $HOST_CHOSEN\n"
	
	cat $HOST_CHOSEN.phys_info | awk ' ! / *#/ { if ($1 == "CPU") { print $2 } }' | read CPU_number
    #prompt_value "Number of virtual CPUs" $CPU_number
    #echo "$RESULT CPUs"
    #CPU_number=$RESULT
        
	cat $HOST_CHOSEN.phys_info | awk ' ! / *#/ { if ($1 == "MEM") { print $2 } }' | read MEM_size
    #prompt_value "VM memory size (MB)" $MEM_size
    #echo "$RESULT MB"
    #MEM_size=$RESULT        
        
    #prompt_value "CPU entitlement(%)" 50
    #echo "$RESULT%"
    CPU_percent=50
}


#----------------------------------------------------------------------------
function MenuPredefinedStorage {
 
    while true
    do
        STORAGE_TYPE="NODEF"
        clear
        #printHeader " "
        printf "\t  Choose Pre-defined Storage Scenario\n"
        printf "\t---------------------------------------\n\n"
        printf "\t[ 1 ] - Use regular file storage\n\n"
        printf "\t[ 2 ] - Use logical volume storage\n\n"
        printf "\t[ 3 ] - Use disk device storage\n\n"
        printf "\t[ 4 ] - Customized storage configuration\n\n"        
        printf "\n\nChoose option (ENTER returns): "
        read opt

        [ "$opt" ] || { printf "\n\nExiting.\n"; return ; }

        case $opt in
            1) STORAGE_TYPE=FILE
                break
                ;; 
            
            2) STORAGE_TYPE=LVOL
                break
                ;;
    
            3) STORAGE_TYPE=DISK
                break
                ;;

            4) STORAGE_TYPE=CUSTOM
                break
                ;;
                
            *) printf "Option $opt invalid.\n"
                sleep 1
                ;;        
        esac
    done
}


#----------------------------------------------------------------------------
function AllocFileStorage {

    while true
    do
        printf "Filesystems available in: %s" "`hostname`"
        df -b
        printf "\nPlease choose the filesystem to be used:"
        read BASE_FS
    done
}

#----------------------------------------------------------------------------
function AllocLogicalVolumeStorage {

	echo "dummy"
}

#----------------------------------------------------------------------------        
function AllocDiskDeviceStorage {

	echo "dummy"
}

#----------------------------------------------------------------------------
function MapDisks {
if [ "$1" = INFO ]
then
	echo "\n\nMap disk volumes to virtual backing stores?"
else
    #MenuPredefinedStorage
	STORAGE_TYPE=CUSTOM
    case $STORAGE_TYPE in
        FILE)
            AllocFileStorage
            ;; 
            
        LVOL)
            AllocLogicalVolumeStorage
            ;;
    
        DISK)
            AllocDiskDeviceStorage
            ;;

        CUSTOM)
            #printHeader "Mapping Disk Volumes "
            #echo "\n\nUsing configuration files for host: $HOST_CHOSEN\n"
            #print_source_disk $HOST_CHOSEN
            map_disk $HOST_CHOSEN            
            ;;        
    esac
fi
}

#----------------------------------------------------------------------------
function MapNetwork {

	if [ "$1" = INFO ]
	then
		echo "\n\nMap network interface cards?"
	else
	    #printHeader "Mapping Network Cards"
		#print_source_net $HOST_CHOSEN
		#echo "\n\nNetwork cards on $SYSTEM_NAME:\n"
		
		#printf "%-5s %-18s %s\n" NIC IP STATUS
		#echo "------------------------------------"
		get_lan_cards
		#get_vswitches
		map_network $HOST_CHOSEN
	fi
}

#----------------------------------------------------------------------------
function GenerateHpvmcreateCmdLine {

	if [ "$1" = INFO ]
	then
		echo "\n\nGenerate hpvmcreate command line?"       
	else
		OUT_FILE=vm${HOST_CHOSEN}.sh
		init_out_file > $OUT_FILE
		create_vm_cmd $HOST_CHOSEN > /dev/null
		chmod u+x $OUT_FILE
		
		printf "hpvmcreate command line generation complete.\n" 
		printf "Ready to create the virtual machine.\n" 
		prompt_AnyKey
		`pwd`"/${OUT_FILE}" || { return 1 ; }
	fi
}

#----------------------------------------------------------------------------
function intMain {

com_get_system_name

clear
#printHeader "Virtual Machine Creation"
get_files_list

for prog in  MapSystemResources MapDisks MapNetwork GenerateHpvmcreateCmdLine
do
	$prog INFO
    prompt_next
    case $RESULT in
        	YES)	
				;; # do nothing, for now.
                
            SKIP)
                echo "Task skipped."
                continue # skip next interation
                ;;
				
            QUIT)
               	exit # Bail out.
                ;;
				
            *)
                echo "Internal error."
                exit
    esac
    $prog
done

exit 0

}

#----------------------------------------------------------------------------
# arg 1 - P2VAPP
# arg 2 - parameter file name
# arg 3 - Name of the VM to be created
#
function unattendedMain {

	file_phys=$2
	VM_NAME=$3
	HOST_CHOSEN=${file_phys%.*}
	HOST_CHOSEN=${HOST_CHOSEN##*/}
	
	MapSystemResources 
	MapDisks CUSTOM
	MapNetwork 
	GenerateHpvmcreateCmdLine || { return 1 ; }
}


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

if [ $# = 0 ]
then
	intMain
else
	unattendedMain $@
	exit $?
fi 

