#!/usr/bin/ksh
#
# AnalyzeSystemResources.sh
#
# This is a generic version of the scripts used on Apache and
# OpenView servers consolidation.
#
# It now just gets information on the CPUs, Memory, LAN cards
# and disk volumes used in the host.
#
# 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. 
#


trap clean_up_temps EXIT int

APACHE_CONF=/opt/hpws/apache/conf/httpd.conf
TEMP_MOUNT_POINTS=/tmp/GatherApacheDiskUsage.mount.$$
TEMP_DISK_LIST=/tmp/GatherApacheDiskUsage.disk.$$

if [ "$1" ]; then
    export TERM=$1
fi

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


#-----------------------------------------------------------------------------
function clean_up_temps {
	rm $TEMP_MOUNT_POINTS $TEMP_MOUNT_POINTS.tmp 2> /dev/null
}


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

#-----------------------------------------------------------------------------
function init_net_header_out {
	echo "# "
    echo "# ------------------------------------------"
	echo "#  Server Network Parameters"
	echo "# ------------------------------------------"
	echo "# "
	echo "# Created on "`date`
    echo "# "
	echo "# Type    NIC Id      IP         STATUS(up/down)"
    echo "# "
}

#-----------------------------------------------------------------------------
function init_disk_header_out {
	echo "# "
    echo "# ------------------------------------------"
	echo "#  Server Disk Parameters"
	echo "# ------------------------------------------"
	echo "# "
	echo "# Created on "`date`
    echo "# "
	echo "# Device    Device    Device"
	echo "# Type      Path      Size(MB)"
    echo "# "
}


#-----------------------------------------------------------------------------
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 "# "

/usr/contrib/bin/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 {
    if [ "$1" ]
    then
        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 2> /dev/null | 
                        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
                            printf "ceil(%d/1024)" $disk_size | bs | read disk_size
                            echo "DSK $raw_ctd $disk_size"
                        done
                ;;
        esac
    fi
}


function SystemResourcesRetrieving {
#-----------------------------------------------------------------------------
# ------ System Resources Retrieving -------
#-----------------------------------------------------------------------------

if [ "$1" = INFO ]
then
	echo
	echo 
	echo " Perform System Resources Retrieving ?"
	echo 
else
    printHeader " System Resources Retrieving"
	com_get_system_name
	OUT_FILE=$SYSTEM_NAME.phys_info
	get_board_params | tee $OUT_FILE
fi

}

#-----------------------------------------------------------------------------
function NetworkResourcesRetrieving {
#-----------------------------------------------------------------------------
# ------ Network Resources Retrieving -------
#-----------------------------------------------------------------------------

if [ "$1" = INFO ]
then
	echo
	echo 
	echo "Perform Network Resources Retrieving ?"
   	echo 
else
    printHeader " Network Resources Retrieving"
	init_net_header_out >> $OUT_FILE

	echo "Network cards on $SYSTEM_NAME:\n"

	printf "%-5s %-18s %s\n" NIC IP STATUS
	echo "------------------------------------"
	get_lan_cards | tee -a $OUT_FILE
fi

}

#-----------------------------------------------------------------------------
function DiskResourcesRetrieving {
#-----------------------------------------------------------------------------
# ------ Disk Resources Retrieving -------
#-----------------------------------------------------------------------------

if [ "$1" = INFO ]
then
	echo
	echo 
	echo "  Perform Disk Resources Retrieving ?"
	echo 
else

    printHeader "Disk Resources Retrieving"
	init_disk_header_out >> $OUT_FILE

	ROOT_VG=`lvlnboot -v 2> /dev/null | awk ' /Boot Definitions for Volume Group/ { print $6 }' | awk -F: '{ print $1 }'`

	echo "Root Volume Group Defined: $ROOT_VG"
	echo "------------------------------------"
	echo "\nDisks from Root VG:"
	get_volume_details $ROOT_VG | tee -a $OUT_FILE

	echo
    echo "Other disks allocated in Volume Groups:"
    for i in "`vgdisplay 2> /dev/null | grep -i 'vg name' | grep -v $ROOT_VG | awk '{ print $3 }'`"
    do
		get_volume_details $i | tee -a $OUT_FILE
    done
    echo
fi

}

#-----------------------------------------------------------------------------
function ParseInputParametersFile {

if [ "$1" = INFO ]
then
	echo 
	echo " Parse Input Parameters File ?"
	echo 
else
    if [ "$1" = P2VAPP ]
    then
        find_param_file
        if [ $PARAMETER_FILE_NAME != "NONE" ]
        then
            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 depots_array `parse_param_file_keyword $PARAMETER_FILE_NAME swcomponent`
            set -A disks_array  `parse_param_file_keyword $PARAMETER_FILE_NAME disk`
            set -A IUX_array    `parse_param_file_keyword $PARAMETER_FILE_NAME IUXserver`
            set -A SD_array     `parse_param_file_keyword $PARAMETER_FILE_NAME depotserver`

			dest_param_file=$REMOTE_TEMP_DIR/`hostname`.$PARAM_RESULT_SUFFIX
			if [ $PARAMETER_FILE_NAME != $dest_param_file ]
			then
				cp -p $PARAMETER_FILE_NAME $dest_param_file
			fi
        fi
    else
        find_param_file
        if [ $PARAMETER_FILE_NAME != "NONE" ]
        then
            parse_param_file $PARAMETER_FILE_NAME
        fi
    fi
fi

}


#-----------------------------------------------------------------------------
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
PARAMETER_FILE_NAME=/tmp/${SYSTEM_NAME}.parameters

	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
}


#-----------------------------------------------------------------------------
function parse_param_file {
#
# Receives a file name and scans it to set the internal 
# variables according to the directives found.

PARAM_FILE="$1"

typeset -i i=0

cat $PARAM_FILE | awk ' /dir[ ]*=[ ]*/ { split($0, m, "[ ]*=[ ]*"); printf ("DIR %s\n", m[2]) } ' |
        while read directive value
        do
            dir_param[$i]=$value
            i=$i+1
        done
       
        i=0
        old_cd=`pwd`
        cd /
        for d in ${dir_param[@]}
        do
            printf "Create an archive for this directory?\n"
            printf "[ %s ] :" $d
            prompt_YesNo
            if [ $RESULT = YES ]; then
                printf "Executing archive in background.\n"
                tar cf /var/tmp/${SYSTEM_NAME}_$i.tar '.'$d > /dev/null 2>&1 &
                i=$i+1
                TAR_RUNNING=1
            fi
        done
cd $old_cd       

}


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

TAR_RUNNING=0

if [ "$2" = P2VAPP ]
then
    #ParseInputParametersFile P2VAPP
    SystemResourcesRetrieving  
	NetworkResourcesRetrieving 
	DiskResourcesRetrieving   
    
else

    for prog in \
        ParseInputParametersFile   \
        SystemResourcesRetrieving  \
        NetworkResourcesRetrieving \
        DiskResourcesRetrieving
    do
        $prog INFO
            prompt_next
            case $RESULT in
                YES)	;; # do nothing, for now.
                    
                SKIP)
                    echo "Task skipped."
                    continue # skip next interation
                    ;;
                
                QUIT)
                    break # Bail out.
                    ;;
                    
                *)
                    echo "Internal error."
                    exit
            esac
            $prog
    done

    if [ $TAR_RUNNING = 1 ]; then
        printf "\nThere are tasks running in background,\nplease wait to allow them to complete." 
        wait
        printf "All tasks completed."
    fi
fi

exit 0

}

# ###########################################################################
#                                                                          
#    - - - - - - - - - - - -  Program Start - - - - - - - - - - - -        
#                                                                          
# ###########################################################################


Main $@
