#!/bin/sh

#############################################################
#  Copyright (c) 2002-2014, EMC Corporation.  All Rights Reserved.
#
#  To configure PowerPath in a Boot-From-SAN setup on RHEL6, SLES11 and OL6.
#############################################################

#-----------------------------------------------------
##    Variables
#-----------------------------------------------------

REDHAT=/etc/redhat-release
SLES=/etc/SuSE-release
DRIVERS_LOC=/sys/bus/pci/drivers
SCRIPT_NAME=$(basename $0)
SCSI_HOSTS=/sys/class/scsi_host
FC_HOSTS=/sys/class/fc_host
FSTAB=/etc/fstab
TMP_FSTAB=/tmp/tmp_${SCRIPT_NAME}_fstab
TMP1_FSTAB=/tmp/tmp1_${SCRIPT_NAME}_fstab
LVM=/etc/lvm/lvm.conf
TMP_LVM=/tmp/tmp_${SCRIPT_NAME}_lvm.conf
TMP1_LVM=/tmp/tmp1_${SCRIPT_NAME}_lvm.conf
MENU_LST=/boot/grub/menu.lst
TMP_MENU_LST=/tmp/tmp_${SCRIPT_NAME}_menu.lst
TMP1_MENU_LST=/tmp/tmp1_${SCRIPT_NAME}_menu.lst
POWERPATH=/etc/init.d/PowerPath
PP_RHEL6_UNI_DIR=/usr/share/dracut/modules.d/90powerpath
PP_BFS_DONE=/etc/emc/.${SCRIPT_NAME}_done
TMP_PP_ADD_LUN=/tmp/tmp_${SCRIPT_NAME}_add_lun
TMP_EMCP_MAPPING=/tmp/tmp_${SCRIPT_NAME}_export_mapping
DATE=bkp_${SCRIPT_NAME}_$1_$(date "+%b%d%Y_%Hh%Mm%Ss")
TMP_PP_RHEL6_UNI_DIR=/tmp/90powerpath
MIN_BOOT_SIZE=22000
ACTION=no
FORCE=no
PP_BOOT_LUN=no
STATUS=no


#-----------------------------------------------------
##    Usage of the script
#-----------------------------------------------------

USAGE()
{
    echo "---------------------------"
    echo ""
    echo "Usage:"
    echo "  ${SCRIPT_NAME} <operation>"
    echo ""
    echo "  where <operation> is one of the following:"
    echo "    config  [-force]"
    echo "    remove"
    echo "    upgrade"
    echo "    help"
    echo ""
    echo "---------------------------"
}       

#-----------------------------------------------------
##    HEADER
#-----------------------------------------------------
HEADER()
{
    echo "$1" | awk '{
    i=66;k=1
    for(k=1;k<i;k++)printf("-")
    printf("\n")}'
}

#-----------------------------------------------------
##   ERROR HEADER
#-----------------------------------------------------
ERROR_HEADER()
{
    echo
    echo "$1" | awk '{
    i=66;k=1
    for(k=1;k<i;k++)printf("*")
    printf("\n")}'
}

#-----------------------------------------------------
##   Cleanup and exit
#-----------------------------------------------------
CLEANUP()
{
    # Cleanup temp files from the system.
    for tmp_files in $TMP_FSTAB $TMP1_FSTAB $TMP_LVM $TMP1_LVM \
                     $TMP_MENU_LST $TMP1_MENU_LST $TMP_EMCP_MAPPING \
                     $TMP_PP_ADD_LUN
    do

        if [ -f $tmp_files ]; then
            rm -f $tmp_files
        fi

    done
  
    if [ -d $TMP_PP_RHEL6_UNI_DIR ]; then
       rm -rf $TMP_PP_RHEL6_UNI_DIR
    fi
}

ERROR_EXIT()
{
    # Exit the script for any error.
    CLEANUP 
    exit 1
}

#-----------------------------------------------------
##   Messages to System log
#-----------------------------------------------------
PP_LOGGER()
{
    msg=$*
    type logger > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        logger -t $SCRIPT_NAME ${msg}
    fi
}


#-----------------------------------------------------
##    Audit Messages
#-----------------------------------------------------
AUDIT_MESSAGE()
{
    if [[ ${ACTION} == "config" && $FORCE == "-force" ]]; then
        PP_LOGGER info: cmd=${SCRIPT_NAME}: ${ACTION}: \'-force\' \
                        \(user ID real=$(id -u) effective=$(id -g)\)
    elif [[ $ACTION == "remove" || $ACTION == "upgrade" ||\
            $ACTION == "config" ]]; then
        PP_LOGGER info: cmd=${SCRIPT_NAME}: ${ACTION} \
                        \(user ID real=$(id -u) effective=$(id -g)\)
    fi
}

#-----------------------------------------------------
##    Messages
#-----------------------------------------------------
MESSAGES()
{
    # Info and error messages use by the script.
    case $1 in
    msg_phase1)

        AUDIT_MESSAGE
        HEADER
        echo "PHASE 1: VERIFICATION PHASE"
        HEADER
        PP_LOGGER info: PHASE 1: VERIFICATION PHASE.

    ;;
    msg_phase2_config)

        HEADER
        echo "PHASE 2: CONFIGURATION PHASE"
        HEADER
        PP_LOGGER info: PHASE 2: CONFIGURATION PHASE.

    ;;
    msg_pp_not_installed)

        ERROR_HEADER
        echo "ERROR: PowerPath is not installed." 
        ERROR_HEADER
        PP_LOGGER error: PowerPath is not installed.
        ERROR_EXIT

    ;;
    msg_pp_not_running)

        ERROR_HEADER
        echo "ERROR: PowerPath is not running."
        ERROR_HEADER
        PP_LOGGER error: PowerPath is not running.
        ERROR_EXIT

    ;;
    msg_phase2_remove)

        HEADER
        echo "PHASE 2: REMOVAL PHASE"
        HEADER
        PP_LOGGER info: PHASE 2: REMOVAL PHASE.

    ;;
    msg_phase2_upgrade)

        HEADER
        echo "PHASE 2: UPGRADE PHASE"
        HEADER
        PP_LOGGER info: PHASE 2: UPGRADE PHASE.

    ;;
    msg_config_success)

        HEADER
        echo "INFO: Successfully Completed."
        echo "      Restart the server for the configuration to take effect."
        HEADER
        PP_LOGGER info: Successfully Completed. Restart the server for the configuration to take effect.
        CLEANUP

    ;;
    msg_remove_success)

        HEADER
        echo "INFO: Successfully Completed."
        echo "      Restart the server and then un-install PowerPath."
        HEADER
        PP_LOGGER info: Successfully Completed. Restart the server and then un-install PowerPath.
        CLEANUP

    ;;
    msg_upgrade_success)

        HEADER
        echo "INFO: Successfully Completed."
        echo "      Please proceed for Kernel Upgrade."
        HEADER
        PP_LOGGER info: Successfully Completed. Please proceed for Kernel Upgrade.
        CLEANUP

    ;;
    msg_not_supported_kernel)

        AUDIT_MESSAGE
        ERROR_HEADER
        echo "ERROR: The script ${SCRIPT_NAME} is NOT supported on this kernel."
        ERROR_HEADER
        PP_LOGGER error: The script ${SCRIPT_NAME} is NOT supported on this kernel.

    ;;
    msg_not_supported_config)

        ERROR_HEADER
        echo "ERROR: Not a supported PowerPath Boot-From-SAN configuration."
        ERROR_HEADER
        PP_LOGGER error: Not a supported PowerPath Boot-From-SAN configuration.
        ERROR_EXIT

    ;;
    msg_no_force_option)

         ERROR_HEADER
         echo "ERROR: Additional LUN(s) are available other than Boot LUN"
         echo "       and Root LVM LUN(s), please use \"-force\" option."
         ERROR_HEADER
         PP_LOGGER error: Additional LUN\(s\) are available other than Boot LUN and Root LVM LUN\(s\), please use \'-force\' option.
         ERROR_EXIT

    ;;
    msg_check_fstab)

         ERROR_HEADER
         echo "ERROR: Either /etc/fstab file is missing"
         echo "       or /boot entry is not found." 
         ERROR_HEADER
         PP_LOGGER error: Either \/etc\/fstab file is missing or \/boot entry is not found.
         ERROR_EXIT

    ;;
    msg_check_boot_size)

         ERROR_HEADER
         echo "ERROR: Please ensure enough space in /boot."
         ERROR_HEADER
         PP_LOGGER error: Please ensure enough space in \/boot.
         ERROR_EXIT

    ;;
    msg_check_lvm)

         ERROR_HEADER
         echo "ERROR: \'filter\' not found in ${LVM}."
         ERROR_HEADER
         PP_LOGGER error: \'filter\' not found in ${LVM}.
         ERROR_EXIT

    ;;
    msg_check_boot_in_use)

         ERROR_HEADER
         echo "ERROR: /boot is in use."
         ERROR_HEADER
         PP_LOGGER error: \/boot is in use.
         ERROR_EXIT

    ;;
    msg_check_menu_lst)

         ERROR_HEADER
         echo "ERROR: ${MENU_LST} failed to validate."
         ERROR_HEADER
         PP_LOGGER error: ${MENU_LST} failed to validate.
         ERROR_EXIT

    ;;
    msg_remove_device)

         ERROR_HEADER
         echo "ERROR: LUN(s) in use, can't proceed."
         ERROR_HEADER
         PP_LOGGER error: LUN\(s\) in use, can\'t proceed.
         ERROR_EXIT

    ;;
    msg_fstab_update_umount)

         ERROR_HEADER
         echo "ERROR: /boot in use, can't umount."
         ERROR_HEADER
         PP_LOGGER error: \/boot in use, can\'t umount.

    ;;
    msg_fstab_update_mount)

         ERROR_HEADER
         echo "ERROR: Failed to update ${FSTAB}."
         ERROR_HEADER
         PP_LOGGER error: Failed to update ${FSTAB}.

    ;;
    msg_lvm_update)

         ERROR_HEADER
         echo "ERROR: Failed to update ${LVM}."
         ERROR_HEADER
         PP_LOGGER error: Failed to update ${LVM}.

    ;;
    msg_initramfs_create)

         ERROR_HEADER
         echo "ERROR: Failed to create ${initramfs}."
         ERROR_HEADER
         PP_LOGGER error: Failed to create ${initramfs}.

    ;;
    msg_menulst_update)

         ERROR_HEADER
         echo "ERROR: Failed to update ${MENU_LST}."
         ERROR_HEADER
         PP_LOGGER error: Failed to update ${MENU_LST}.

    ;;
    msg_pp_script)

         ERROR_HEADER
         echo "WARNNING: $POWERPATH is missing."
         ERROR_HEADER
         PP_LOGGER warnning: $POWERPATH is missing.

    ;;
    msg_pp_script1)

         ERROR_HEADER
         echo "ERROR: $POWERPATH startup script is missing."
         echo "       Please re-install PowerPath."
         ERROR_HEADER
         PP_LOGGER error: $POWERPATH startup script is missing, Please re-install PowerPath.
         ERROR_EXIT

    ;;
    msg_pp_rhel6bfs_dir)

         ERROR_HEADER
         echo "ERROR: Directory ${PP_RHEL6_UNI_DIR} is missing."
         echo "       Please re-install PowerPath."
         ERROR_HEADER
         PP_LOGGER error: Directory ${PP_RHEL6_UNI_DIR} is missing. Please re-install PowerPath.
         ERROR_EXIT

    ;;
    msg_pp_bfs_configured)

         AUDIT_MESSAGE
         ERROR_HEADER
         echo "ERROR: PowerPath is already configured."
         ERROR_HEADER
         PP_LOGGER error: PowerPath is already configured.
         ERROR_EXIT

    ;;
    msg_pp_bfs_not_configured)

         AUDIT_MESSAGE
         ERROR_HEADER
         echo "ERROR: PowerPath is not configured on Boot-From-SAN."
         ERROR_HEADER
         PP_LOGGER error: PowerPath is not configured on Boot-From-SAN.
         ERROR_EXIT

    ;;
    msg_incorrect_input)

         ERROR_HEADER
         echo "ERROR: Invalid option."
         ERROR_HEADER

    ;;
    msg_rollback)

         HEADER
         echo "INFO: ROLLBACK STARTED"
         HEADER
         PP_LOGGER info: ROLLBACK STARTED.

    ;;
    msg_ctrl_c_rollback)

         ERROR_HEADER
         echo "ERROR: Interrupt signal Ctrl + C identified."   
         echo "       Starting rollback."
         ERROR_HEADER
         PP_LOGGER error: Ctrl + C Interpreted, proceeding for rollback.

    ;;
    msg_rollback_success)

         HEADER
         echo "INFO: Restored Original Configuration."
         echo "      Please fix above error and try again."
         HEADER
         PP_LOGGER info: Restored Original Configuration. Please fix the error and try again.
         ERROR_EXIT

    ;;
    msg_ctrl_c_no_change)

         HEADER
         echo "INFO: No changes made to the system files." 
         HEADER
         PP_LOGGER info: No changes made to the system files.
         ERROR_EXIT

    ;;
    msg_insufficient_permission)

         AUDIT_MESSAGE
         HEADER
         echo "ERROR: Insufficient user privilege." 
         HEADER
         PP_LOGGER error: Insufficient user privilege \(user ID real=$(id -u) effective=$(id -g)\).
         ERROR_EXIT

    ;;
    msg_ppme_present)

         HEADER
         echo "ERROR: PowerPath migrations are present." 
         echo "       Please cleanup the migrations and then reissue the ${SCRIPT_NAME}."
         HEADER
         PP_LOGGER error: PowerPath migrations are present. Please cleanup the migrations and then reissue the ${SCRIPT_NAME}.
         ERROR_EXIT

    ;;
    esac

}

#-----------------------------------------------------
##   Rollback Stages
#-----------------------------------------------------
ROLLBACK_STAGE0()
{
     # Rollback the PowerPath pseudo devices and their mapping. 
     if [[ -f ${TMP_PP_ADD_LUN} || ${STAGE} == "LUN_REMOVED" ]]; then
         FC_SCAN_SUB
         powermt config
         UDEV_SETTLE
         emcpadm import_mappings -f ${TMP_EMCP_MAPPING} > /dev/null 2>&1
         echo $PP_LVM_LUN | grep emcpower  > /dev/null 2>&1

         if [[ $? == 0 ]]; then
             pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                         awk -F "=" '{ print $NF }' | egrep -v ${PP_LVM_LUN} | grep -v ${PP_BOOT_LUN})
         else
             pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                         awk -F "=" '{ print $NF }' | grep -v ${PP_BOOT_LUN})
         fi

         LUN_ID ${pp_pseudo_names}
         echo "   Dynamic LUN(s) addition: $(echo ${device_all})"
         rm -f ${TMP_PP_ADD_LUN}
     fi
}

ROLLBACK_STAGE1()
{

    # Rollback the fstab file.
    echo "   Reverting ${FSTAB}"
    mv -f ${FSTAB}_${DATE} ${FSTAB}
    umount /boot > /dev/null 2>&1
    mount /boot > /dev/null 2>&1
    ROLLBACK_STAGE0

}

ROLLBACK_STAGE2()
{

    # Rollback the lvm.conf file.
    echo "   Reverting ${LVM}"
    mv -f ${LVM}_${DATE} ${LVM}
    vgscan -v  > /dev/null 2>&1
    lvmdiskscan  > /dev/null 2>&1
    ROLLBACK_STAGE1

}

ROLLBACK_STAGE3()
{

    # Rollback the PowerPath RHEL6 un-install directory
    # and initrd image. 
    if [[ $ACTION == "remove" && $VERSION == "RHEL6" ]]; then
        if [ -d ${TMP_PP_RHEL6_UNI_DIR} ]; then
            mv -f ${TMP_PP_RHEL6_UNI_DIR} ${PP_RHEL6_UNI_DIR}
        fi
    fi

    if [ -f ${initramfs}_${DATE} ]; then
        echo "   Reverting ${initramfs}"
        mv -f  ${initramfs}_${DATE} ${initramfs} 
    fi
    ROLLBACK_STAGE2

}

ROLLBACK_STAGE4()
{
    # Rollback the PowerPath startup script
    # and  grup/menu.lst file.
    if [[ ${pp_file_moved} == "yes" ]]; then
        echo "   Reverting $POWERPATH"
        mv -f ${POWERPATH}.${DATE} ${POWERPATH}
    fi

    echo "   Reverting ${MENU_LST}"
    mv -f ${MENU_LST}_${DATE} ${MENU_LST}
    ROLLBACK_STAGE3

}
#-----------------------------------------------------
##   Rollback MAIN
#-----------------------------------------------------

ROLLBACK()
{
    # Script detected error during configuration, 
    # hence rolling back the original configuration

    MESSAGES msg_rollback

    case $STAGE in
    STAGE1)
        ROLLBACK_STAGE1
    ;;
    STAGE2)
        ROLLBACK_STAGE2
    ;;
    STAGE3)
        ROLLBACK_STAGE3
    ;;
    STAGE4)
        ROLLBACK_STAGE4
    ;;
    esac

    MESSAGES msg_rollback_success

}

#-----------------------------------------------------
##   Ctrl + C Rollback
#-----------------------------------------------------
CTRL_C()
{
    # Script detected Ctrl + C configuration, 
    # hence rolling back the original configuration.
    MESSAGES msg_ctrl_c_rollback

    if [[ $STAGE == LUN_REMOVED ]]; then
        ROLLBACK_STAGE0
        MESSAGES msg_ctrl_c_no_change 
    elif [[ $STAGE != "" ]]; then
        ROLLBACK
    else
        MESSAGES msg_ctrl_c_no_change 
    fi

}

#-----------------------------------------------------
##   UDEV settle
#-----------------------------------------------------

UDEV_SETTLE()
{
    # Waiting for Udev to settle down.  
    if [ -x /sbin/udevadm ]; then
        /sbin/udevadm settle --timeout=360
        sleep 2
    elif [ -x /sbin/udevsettle ]; then
        /sbin/udevsettle --timeout=360 
        sleep 2
    fi

}

#-----------------------------------------------------
##    SCANNING HBA's 
#-----------------------------------------------------

FC_SCAN_SUB()
{
    # Scanning the HBA for dynamic LUN(s) addition.
    for host_port in $(ls -1 -d ${DRIVERS_LOC}/*/*/host* |\
                      awk -F "host" '{ print $NF }') 
    do

        if [ -f  ${SCSI_HOSTS}/host${host_port}/scan ]; then
            echo "- - -" > ${SCSI_HOSTS}/host${host_port}/scan
            UDEV_SETTLE
        fi

    done

    unset host_port
    
    # Scanning iSCSI and FCoE for dynamic LUN(s) addition,
    # if -force is specified.
    for host_port in $(ls -1 ${SCSI_HOSTS}/ |\
                     awk -F "host" '{ print $NF }')
    do

        if [ -f ${SCSI_HOSTS}/host${host_port}/proc_name ]; then
            dev_proc_name=$(cat ${SCSI_HOSTS}/host${host_port}/proc_name |\
                          cut -c 1-5)
            if [[ ${dev_proc_name} == "fcoe" ||\
                  ${dev_proc_name} == "iscsi" ]]; then
                echo "- - -" > ${SCSI_HOSTS}/host${host_port}/scan
                UDEV_SETTLE
            fi

        fi

    done

}

#-----------------------------------------------------
##    Dynamic LUN(s) Removal 
#-----------------------------------------------------
REMOVE_DEVICE() 
{
    # Removal additional LUN(s) from PowerPath and system,
    # if -force option is specified.

    echo $PP_LVM_LUN | grep emcpower  > /dev/null 2>&1

    if [[ $? == 0 ]]; then

        pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                     awk -F "=" '{ print $NF }' | egrep -v $PP_LVM_LUN | grep -v $PP_BOOT_LUN)
    else
        pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                     awk -F "=" '{ print $NF }' | grep -v $PP_BOOT_LUN)
    fi

    LUN_ID ${pp_pseudo_names}
    echo "   Dynamic LUN(s) removal: $(echo $device_all)"

    for pp_pseudo in $(echo $pp_pseudo_names)
    do
        native_dev_names=$(powermt display dev=$pp_pseudo |\
                         egrep 'active|standby|unlic' | grep -v unknown |\
                         sed -ne 's:\(.*\) \(sd[a-z]*\) \(.*\):\2:p')
        powermt remove dev=$pp_pseudo

        if [ $? -eq 0 ]; then
            STAGE=LUN_REMOVED

            for native_dev in $(echo $native_dev_names)
            do

                if [ -f /sys/block/${native_dev}/device/delete ]; then
                    echo 1 > /sys/block/${native_dev}/device/delete
                fi

            done

        else 
            sleep 15
            UDEV_SETTLE
            FC_SCAN_SUB
            powermt config
            UDEV_SETTLE
            emcpadm import_mappings -f ${TMP_EMCP_MAPPING} > /dev/null 2>&1
            MESSAGES msg_remove_device
        fi

    done

    touch $TMP_PP_ADD_LUN

}

#-----------------------------------------------------
##   Host Configuration Verification SUB Functions
#-----------------------------------------------------
#-----------------------------------------------------
##   PowerPath Verification 
#-----------------------------------------------------
CHECK_POWERPATH()
{
    lsmod | grep -w emcp > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        rpm -qa | grep EMCpower.LINUX > /dev/null 2>&1

        if [ $? -ne 0 ]; then
            echo "Failed" 
            STATUS="Failed:msg_pp_not_installed"
        else
            echo "Failed" 
            STATUS="Failed:msg_pp_not_running"
        fi

    else
        echo "Installed"
    fi
}

#-----------------------------------------------------
##   LUN ID and NICE NAME
#-----------------------------------------------------
LUN_ID()
{
    unset device_all

    for device in $@ ; do
       emcp_lun=$(powermt display dev=$device | grep emcpower |\
                awk -F "=" '{ print $NF }')

       powermt display dev=${emcp_lun} | egrep '^VNX|^CLARiiON' > /dev/null 2>&1
       if [[ $? == 0 ]]; then
           dev_name=$(powermt display dev=${emcp_lun} | awk -F "[" '/^Logical/ { print $2 }' |\
                      sed -e 's/\]//g')
           device_all="${emcp_lun}:${dev_name} ${device_all}"
       else
           dev_name=$(powermt display dev=${emcp_lun} | awk -F "=" '/^Logical/ { print $2 }')
           length=${#dev_name}

           if (( ${length} <= 8 )); then
               device_all="${emcp_lun}:${dev_name} ${device_all}"
           else
               device_all="${emcp_lun}:${dev_name:(-8)} ${device_all}"
           fi

       fi

    done
}

#-----------------------------------------------------
##   Verification of Boot LUN
#-----------------------------------------------------
CHECK_BOOT_LUN()
{

    boot_lun=$(df -h /boot | grep '/boot' |  awk '{ print $1 }' |\
             awk -F "/" '{ print $NF }' |\
             sed 's/[1-9]//g')  > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        echo "Failed" 
        STATUS="Failed:msg_not_supported_config"
    else
        powermt display dev=$boot_lun > /dev/null 2>&1

        if [ $? -ne 0 ]; then
            echo "Failed" 
            STATUS="Failed:msg_not_supported_config"
        else
            LUN_ID $boot_lun

            if [[ $device_all == "${boot}: " ]]; then
                unset emcp_lun
                emcp_lun=$(powermt display dev=$boot_lun |\
                         grep emcpower | awk -F "=" '{ print $NF }')
                echo $emcp_lun
            else
                echo $device_all
            fi

        fi

    fi

}

#-----------------------------------------------------
##   Verification of Boot LUN
#-----------------------------------------------------
CHECK_LVM_LUN()
{

    vg_lv=$(mount | grep 'on / type' | awk '{ print $1 }')  > /dev/null 2>&1
    lvdisplay $vg_lv  2>/dev/null > /dev/null 2>&1
    if [[ $? != 0 ]]; then
        STATUS="Failed:msg_not_supported_config"
    fi
    
    vg_name=$(lvdisplay $vg_lv  2>/dev/null | grep 'VG Name' |\
              awk '{ print $NF }')  > /dev/null 2>&1
    devices=$(pvs  2>/dev/null | grep $vg_name | awk '{ print $1 }' |\
              sed 's/[0-9]//g' | awk -F '/' '{ print $NF }' | sort -u )  > /dev/null 2>&1

    for pv_emcp_dev in $devices
    do
       powermt display dev=$pv_emcp_dev  > /dev/null 2>&1

       if [[ $? == 0 ]]; then
           if [[ $PP_LVM_LUN == "" ]]; then
               PP_LVM_LUN=$(powermt display dev=$pv_emcp_dev |\
                            grep emcpower | awk -F "=" '{ print $NF "$"}')
           else
               PP_LVM_LUN="${PP_LVM_LUN} $(powermt display dev=$pv_emcp_dev |\
                             grep emcpower | awk -F "=" '{ print $NF "$" }')"
           fi
       fi

    done

    pv_devices=$(echo $PP_LVM_LUN | sed 's/\$/ /g') > /dev/null 2>&1
    LUN_ID $pv_devices
    lvm_count=0
    echo $pv_devices | grep "\<${emcp_lun}\>" > /dev/null 2>&1

    if [[ $? != 0 ]]; then
        lvm_count=1
    fi

    for count in ${pv_devices}
    do
       lvm_count=$(expr $lvm_count + 1)
    done

    if [[ $device_all == "${boot}: " ]]; then
         unset emcp_lun
         emcp_lun=$(powermt display dev=$boot_lun |\
                   grep emcpower | awk -F "=" '{ print $NF }')
         echo $emcp_lun
    else
         echo $device_all
    fi

    PP_LVM_LUN=$(echo $PP_LVM_LUN | sed 's/ /\|/g')  > /dev/null 2>&1

}

#-----------------------------------------------------
##   Verification of additional LUNs on the system
#-----------------------------------------------------

CHECK_LUNS()
{
    num_device=$(powermt display dev=all | grep emcpower | wc -l)

    if [[ $num_device > $lvm_count ]]; then
         echo "Available" 
         STATUS="Available"
    elif [[ $num_device == $lvm_count ]]; then
         echo "Not Available"
    else
         echo "Available" 
         STATUS="Available"
    fi
}

#-----------------------------------------------------
##   Verification PPME migration
#-----------------------------------------------------
CHECK_PPME()
{
    if [ -f /sbin/powermig ]; then
        powermig info -all | grep "No migrations found." > /dev/null 2>&1

        if [ $? -ne 0 ]; then
            echo "Available"      
            STATUS="Failed:msg_ppme_present"
        else
            echo "No migration"
        fi

    else
        echo "No migration"
    fi
}

#-----------------------------------------------------
##   fstab Verification for /boot entry
#-----------------------------------------------------
CHECK_FSTAB()
{
    if [ -f $FSTAB ]; then
        cat $FSTAB | grep -v "^[ \t]*#" | grep "\/boot " > /dev/null 2>&1

        if [ $? -eq 0 ]; then
            echo "/boot found" 
        else
            echo "Failed" 
            STATUS="Failed:msg_check_fstab"
        fi

    else
        echo "Failed" 
        STATUS="Failed:msg_check_fstab"
    fi

}

#-----------------------------------------------------
##   Verify /boot available free size
#-----------------------------------------------------
CHECK_BOOT_SIZE()
{

    size=$(df -k /boot | awk '{ print $4 }' |\
         awk '/[0-9]/ {version=$NF} END {print version}')

    if [ "$size" -ge "$MIN_BOOT_SIZE" ]; then
        echo "Available"
    else
        echo "Failed"
        STATUS="Failed:msg_check_boot_size"
    fi

}

#-----------------------------------------------------
##   Verify /boot Device Open
#-----------------------------------------------------
CHECK_BOOT_IN_USE()
{

    fuser /boot > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        STATUS="Failed:msg_check_boot_in_use"
    fi

}

#-----------------------------------------------------
##   LVM Filter Verification
#-----------------------------------------------------
CHECK_LVM()
{

    if [ -f $LVM ]; then
        cat $LVM | sed 's/^[ \t]*filter/filter/' |\
                   grep ^filter > /dev/null 2>&1

        if [ $? -eq 0 ]; then
            echo "Filter found"
        else
            echo "Failed"
            STATUS="Failed:msg_check_lvm"
        fi

    else
        echo "Failed"
        STATUS="Failed:msg_check_lvm"
    fi

}

#-----------------------------------------------------
##   Menu.lst Verification
#-----------------------------------------------------
CHECK_MENU_LST_SUB()
{

    default_num=$(cat $MENU_LST | grep "^[ \t]*default" |\
                awk -F " |=" '{ print $NF }')
    cat $MENU_LST | grep "^[ \t]*default" > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        default_num=0
    fi

    (( a = default_num + 1 ))

    kernel=$(cat $MENU_LST | sed -e 's/^[ \t]*//g' -e '/^[ \t]*$/d' |\
           awk -v n=$a '/^title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
           awk '/^kernel/ {Kernel=$2} END {print Kernel}' |\
           awk -F "/" '{ print $NF }')
    initrd=$(cat $MENU_LST | sed -e 's/^[ \t]*//g' -e '/^[ \t]*$/d' |\
           awk -v n=$a '/^title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
           awk '/^initrd/ {Initrd=$2} END {print Initrd}' |\
           awk -F "/" '{ print $NF }')

}

CHECK_MENU_LST()
{

    if [ -f $MENU_LST ]; then
        CHECK_MENU_LST_SUB

        if [[ $kernel != "" && $initrd != "" ]]; then
            echo "Validated"
        else
            echo "Failed"
            STATUS="Failed:msg_check_menu_lst"
        fi

    else
        echo "Failed"
        STATUS="Failed:msg_check_menu_lst"

    fi

}
#-----------------------------------------------------
##   Call Messages 
#-----------------------------------------------------
CALL_MESSAGES()
{

    if [[ ${STATUS%%:*} == Failed ]]; then
        EXIT=${STATUS##*:}
        MESSAGES $EXIT
    fi

}

#-----------------------------------------------------
##   Host Configuration Verification Main Function
#-----------------------------------------------------
CONFIG_CHECK()
{

    echo -n "   Verifying PowerPath ..................... "
    CHECK_POWERPATH
    CALL_MESSAGES
    echo -n "   Verifying Boot LUN ...................... "
    CHECK_BOOT_LUN
    CALL_MESSAGES
    echo -n "   Verifying Root LVM LUN(s) ............... "
    CHECK_LVM_LUN
    CALL_MESSAGES
    echo -n "   Verifying Additional LUN(s) ............. "
    CHECK_LUNS

    if [[ ${STATUS%%:*} == Available ]]; then

        if [[ $ACTION == "config" && $FORCE != "-force" ]]; then
            MESSAGES msg_no_force_option
        fi

    fi

    echo -n "   Verifying PPME Migrations ............... "
    CHECK_PPME
    CALL_MESSAGES

    echo -n "   Verifying $FSTAB .................... "
    CHECK_FSTAB
    CALL_MESSAGES

    if [[ $ACTION != "upgrade" ]]; then
        echo -n "   Verifying /boot space ................... "
        CHECK_BOOT_SIZE
        CALL_MESSAGES
        CHECK_BOOT_IN_USE
        if [[ ${STATUS%%:*} == Failed ]]; then
             EXIT=${STATUS##*:}
             echo "   Verifying /boot ......................... Failed"
             MESSAGES $EXIT
        fi

    fi

    echo -n "   Verifying $LVM ............. "
    CHECK_LVM
    CALL_MESSAGES

    if [[ $ACTION != "upgrade" ]]; then
        echo -n "   Verifying $MENU_LST ........... "
        CHECK_MENU_LST
        CALL_MESSAGES
    fi

}

#-----------------------------------------------------
##    Boot LUN and additional LUN(s) verification 
#-----------------------------------------------------
LUNS_CHECK()
{
    num_device=$(powermt display dev=all | grep emcpower | wc -l)
    partition=$(df -h /boot | grep '/boot' |  awk '{ print $1 }' |\
              awk -F "/" '{ print $NF }' |\
              sed 's/[a-z]//g') > /dev/null 2>&1
    boot_lun=$(df -h /boot | grep '/boot' |  awk '{ print $1 }' |\
              awk -F "/" '{ print $NF }' |\
              sed 's/[1-9]//g')  > /dev/null 2>&1

    if [[ $num_device != $lvm_count ]]; then

        if [[ $FORCE == "-force" ]];then
            UDEV_SETTLE
            emcpadm export_mappings -f $TMP_EMCP_MAPPING  > /dev/null 2>&1
            PP_BOOT_LUN=$(powermt display dev=$boot_lun | grep emcpower |\
                        awk -F "=" '{ print $NF }')  > /dev/null 2>&1
            REMOVE_DEVICE
            powermt release
        else
            MESSAGES msg_no_force_option
        fi

    else
        PP_BOOT_LUN=$(powermt display dev=$boot_lun | grep emcpower |\
                    awk -F "=" '{ print $NF }')  > /dev/null 2>&1
    fi 
}

#-----------------------------------------------------
##    FSTAB Modification 
#-----------------------------------------------------
FSTAB_UPDATE()
{

    if [ -f $FSTAB ]; then
         cp $FSTAB ${FSTAB}_${DATE}
         cp $FSTAB $TMP_FSTAB
         fstab_boot=$(cat $TMP_FSTAB | grep -v "^[ \t]*#" |\
                    grep "\/boot " | awk '{ print $1 }')
         cat $TMP_FSTAB | grep "###${SCRIPT_NAME}###"  > /dev/null 2>&1
         
         if [ $? -ne 0 ]; then
             # Comment out existing /boot enrty.
             sed -i "s%^${fstab_boot}.*%###${SCRIPT_NAME}###$(date)###\n#& \n########\n& %" $TMP_FSTAB
         fi

         if [[ $ACTION == "config" ]]; then
             echo $fstab_boot | grep -v emcpower > /dev/null 2>&1

             if [ $? -eq 0 ]; then
                 # Replace /boot enrty with PowerPath Pseudo device.
                 cat $TMP_FSTAB | sed -e "/\/boot / \
                                  s%^${fstab_boot}%\/dev\/${PP_BOOT_LUN}${partition}%g" > $TMP1_FSTAB
             fi

         elif [[ $ACTION == "remove" || $ACTION == "upgrade" ]]; then
             echo $fstab_boot | grep emcpower > /dev/null 2>&1

             if [ $? -eq 0 ]; then
                 # Replace /boot entry with fileystem UUID.
                 uuid=$(blkid $fstab_boot |\
                      sed -ne 's:\(.*\) \(UUID=.*\) \(.*\):\2:p' |\
                      awk '{ print $1 }' | sed 's/"//g')
                 cat $TMP_FSTAB |\
                     sed -e "/\/boot /  s%^${fstab_boot}%${uuid}%g" > $TMP1_FSTAB
             fi

         fi

         if [ -f $TMP1_FSTAB ]; then
             cp $TMP1_FSTAB $FSTAB
         elif [ -f $TMP_FSTAB ]; then
             cp $TMP_FSTAB $FSTAB
         fi

         while true
         do
             df -h /boot | grep /boot > /dev/null 2>&1

             if [ $? -eq 0 ]; then
                 umount /boot > /dev/null 2>&1

                 if [ $? -ne  0 ]; then
                     echo "Failed"
                     STATUS="Failed:msg_fstab_update_umount"
                     break
                 fi

             else
                 break
             fi

         done

         if [[ ${STATUS%%:*} != Failed ]]; then
             mount /boot > /dev/null 2>&1

             if [ $? -ne 0 ]; then
                 echo "Failed"
                 STATUS="Failed:msg_fstab_update_mount"
             else
                 echo "Done"
             fi

        fi

    else
        echo "Failed"
        STATUS="Failed:msg_fstab_update_mount"
    fi
}

FSTAB_UPDATE_MAIN()
{

    STAGE=STAGE1
    echo -n "   Updating $FSTAB ..................... "
    FSTAB_UPDATE

    if [[ ${STATUS%%:*} == Failed ]]; then
        EXIT=${STATUS##*:}
        MESSAGES $EXIT
        ROLLBACK
    fi
}

#-----------------------------------------------------
##   LVM Filter modification 
#-----------------------------------------------------
LVM_UPDATE()
{

    if [ -f $LVM ]; then
        cp $LVM ${LVM}_${DATE}
        cp $LVM $TMP_LVM
        cat $TMP_LVM | grep "###${SCRIPT_NAME}###"  > /dev/null 2>&1

        if [ $? -ne 0 ]; then
            # Comment out existing lvm filter.
            sed -i "s%^[ \t]*filter.*%    ###${SCRIPT_NAME}###$(date)###\n    #& \n    #########\n& %" $TMP_LVM
        fi

        if [[ $ACTION == "config" ]]; then

            if [[ ${VERSION} == "RHEL6" || ${VERSION} == "SLES11" ]]; then
                cat $TMP_LVM | grep "^[ \t]*filter" |\
                    grep "\"a/emcpower.\*/\"[ \t]*,[ \t]*\"r/sd.\*/\"[ \t]*,[ \t]*\"r/disk.\*/\""  > /dev/null 2>&1

                if [ $? -ne 0 ]; then
                    # Update lvm filter with emcpower device for rhel6 and sles11.
                    cat $TMP_LVM | grep "^[ \t]*filter" | grep "\"a/sd.\*/\"" > /dev/null 2>&1
                    if [ $? -eq 0 ]; then
                        cat $TMP_LVM | sed -e '/^[ \t]*filter/ {
                                            s%\"a/sd.\*/\"%\"a/emcpower.\*/\", \"r/sd.\*/\", \"r/disk.\*/\"%g
                                            s%\"r|/dev/.\*/by-path/.\*|\"%%g
                                            s%\"r|/dev/.\*/by-id/.\*|\"%%g
                                            s%\"r|/dev/.\*/by-name/.\*|\"%%g
                                            s%\"a|/dev/sd.\*|\"%%g
                                            s%\"a/.\*/\"%%g
                                            s%,[ \t]*,[ \t]*,%,%g
                                            s%,[ \t]*,%,%g
                                            s%\[ [ \t]*,%\[ %g
                                            s%,[ \t]*\]% \]%g
                                            }'  > $TMP1_LVM
                    else
                        cat $TMP_LVM | grep "^[ \t]*filter" | grep "\"a/.\*/\"" > /dev/null 2>&1
                        if [ $? -eq 0 ]; then
                            cat $TMP_LVM | sed -e '/^[ \t]*filter/ {
                                               s%\"a/.\*/\"%\"a/emcpower.\*/\", \"r/sd.\*/\", \"r/disk.\*/\"%g
                                               s%\"r|/dev/.\*/by-path/.\*|\"%%g
                                               s%\"r|/dev/.\*/by-id/.\*|\"%%g
                                               s%\"r|/dev/.\*/by-name/.\*|\"%%g
                                               s%\"a|/dev/sd.\*|\"%%g
                                               s%,[ \t]*,[ \t]*,%,%g
                                               s%,[ \t]*,%,%g
                                               s%\[ [ \t]*,%\[ %g
                                               s%,[ \t]*\]% \]%g
                                               }' > $TMP1_LVM
                        else
                            touch $TMP1_LVM
                        fi
                    fi
                    cat $TMP1_LVM | grep "^[ \t]*filter" |\
                                    grep "\"a/emcpower.\*/\"[ \t]*,[ \t]*\"r/sd.\*/\"[ \t]*,[ \t]*\"r/disk.\*/\""  > /dev/null 2>&1

                    if [ $? -ne 0 ]; then
                        sed -i "s%^[ \t]*filter.*%    ###${SCRIPT_NAME} config###$(date)###\n    #& \n    ########\n& %" $TMP_LVM
                        # Overwrite lvm filter, if the lvm filter is failed to update above.
                        cat $TMP_LVM | sed -e '/^[ \t]*filter/  {
                            s%\[.*\]%\[ \"a/emcpower.\*/\", \"r/sd.\*/\", \"r/disk.\*/\" \]%g
                            }'  > $TMP1_LVM
                    fi

                fi

            fi

        elif [[ $ACTION == "remove" || $ACTION == "upgrade" ]]; then
            if [[ ${VERSION} == "RHEL6" || ${VERSION} == "SLES11" ]]; then
                # Update lvm filter for rhel6 and sles11.
                cat $TMP_LVM |  sed -e '/^[ \t]*filter/  {
                    s%\"a/emcpower.*/\"[ \t]*,[ \t]*\"r/sd.\*/\"[ \t]*,[ \t]*\"r/disk.\*/\"%\"r/emcpower.\*/\", \"a/sd.\*/\"%g
                    s%\"r/sd.\*/\"%%g
                    s%\"r|/dev/sd.\*|\"%%g
                    s%,[ \t]*,[ \t]*,%,%g
                    s%,[ \t]*,%,%g
                    s%\[ [ \t]*,%\[ %g
                    s%,[ \t]*\]% \]%g
                    }'  > $TMP1_LVM
                cat $TMP1_LVM | grep "^[ \t]*filter" |\
                    grep "\"r/emcpower.\*/\", \"a/sd.\*/\"" > /dev/null 2>&1

                if [ $? -ne 0 ]; then
                    sed -i "s%^[ \t]*filter.*%    ###${SCRIPT_NAME} remove###$(date)###\n    #& \n    ########\n& %" $TMP_LVM
                    # Overwrite lvm filter, if the lvm filter is failed to update above.
                    cat $TMP_LVM |  sed -e '/^[ \t]*filter/  s%\[.*\]%\[ \"r/emcpower.\*/\", \"a/sd.\*/\" \]%g'  > $TMP1_LVM
                fi

            fi

        fi

        if [ -f $TMP1_LVM ]; then
            cp $TMP1_LVM $LVM
        elif [ -f $TMP_LVM ]; then
            cp $TMP_LVM $LVM
        fi

        vgscan -v  > /dev/null 2>&1
        vgscanvalue=$?
        lvmdiskscan  > /dev/null 2>&1
        lvmdiskscanvalue=$?

        if [[ $vgscanvalue != 0 && $lvmdiskscanvalue != 0 ]]; then
            echo "Failed"
            STATUS="Failed:msg_lvm_update"
        else
            echo Done
        fi

    else
        echo "Failed"
        STATUS="Failed:msg_lvm_update"
    fi

}

LVM_UPDATE_MAIN()
{

    STAGE=STAGE2
    echo -n "   Updating $LVM .............. "
    LVM_UPDATE

    if [[ ${STATUS%%:*} == Failed ]]; then
        EXIT=${STATUS##*:}
        MESSAGES $EXIT
        ROLLBACK
    fi

}

#-----------------------------------------------------
##   Creating initramfs  
#-----------------------------------------------------
INITRAMFS_CREATE()
{ 

    if [ -f $initramfs ]; then
        mv -f $initramfs ${initramfs}_${DATE}
    fi

    CHECK_MENU_LST_SUB

    if [[ $kernel != "" && $initrd != "" ]]; then

        if [[ ${VERSION} == "RHEL6" ]]; then
            # Include or exclude PowerPath in the initramfs.
            dracut $initramfs $(uname -r) 
            initrd_error=$?
        elif [[ ${VERSION} == "SLES11" && -f /boot/$kernel ]]; then

            if [[ $ACTION == "config" ]]; then
                # Include PowerPath in the initrd.
                mkinitrd -i $initramfs  -k /boot/$kernel -f powerpath  > /dev/null 2>&1
                initrd_error=$?
            elif [[ $ACTION == "remove" ]]; then
                # Exclude PowerPath in the initrd.
                mkinitrd -i $initramfs  -k /boot/$kernel  > /dev/null 2>&1
                initrd_error=$?
            fi

        else
            initrd_error=1
        fi

    else
        echo "Failed"
        STATUS="Failed:msg_initramfs_create"
    fi

    if [ ${initrd_error} -eq 0 ]; then
        echo Done
    else
        echo "Failed"
        STATUS="Failed:msg_initramfs_create"
    fi

}

INITRAMFS_CREATE_MAIN()
{
    STAGE=STAGE3

    if [[ $ACTION == "config" ]]; then

        # Initramfs/Initrd name with PowerPath.
        if [[ ${VERSION} == "RHEL6" ]]; then
            initramfs="/boot/initramfs-PP-$(uname -r).img"
        elif [[ ${VERSION} == "SLES11" ]]; then
            initramfs="/boot/initrd-PP-$(uname -r)"
        fi

    elif [[ $ACTION == "remove" ]]; then
        # Initramfs/Initrd name without PowerPath.
        if [[ ${VERSION} == "RHEL6" ]]; then

            if [ -d $TMP_PP_RHEL6_UNI_DIR ]; then
               rm -rf $TMP_PP_RHEL6_UNI_DIR > /dev/null 2>&1
            fi

            # Moving PowerPath bfs directory for removing PowerPath from initramfs.
            mv -f $PP_RHEL6_UNI_DIR /tmp/   > /dev/null 2>&1
            
            initramfs="/boot/initramfs-$(uname -r).img"

        elif [[ ${VERSION} == "SLES11" ]]; then
            initramfs="/boot/initrd-$(uname -r)"
        fi

    fi

#    echo "   Creating ${initramfs}, please wait..."
    echo -n "   Creating $initramfs ..... "
    INITRAMFS_CREATE

    if [[ ${STATUS%%:*} == Failed ]]; then
        EXIT=${STATUS##*:}
        MESSAGES $EXIT
        ROLLBACK
    fi

} 

#-----------------------------------------------------
##   Menu.lst Modification  
#-----------------------------------------------------
MENULST_UPDATE()
{
    if [ -f $MENU_LST ]; then
        cp $MENU_LST ${MENU_LST}_${DATE}
        cat $MENU_LST | grep "^[ \t]*default" > /dev/null 2>&1

        if [ $? -ne 0 ]; then
            cp $MENU_LST $TMP_MENU_LST

            # Insert 'default' value if not present in menu.lst.
            if [[ ${VERSION} == "RHEL6" ]]; then
                sed -i '1idefault=0' $TMP_MENU_LST
            elif [[ ${VERSION} == "SLES11" ]]; then
                sed -i '1idefault 0' $TMP_MENU_LST
            fi

            default_num=0

        else
            default_num=$(cat $MENU_LST | grep "^[ \t]*default" |\
                                          awk -F " |=" '{ print $NF }')
            cp $MENU_LST $TMP_MENU_LST
        fi

        echo " " >> $TMP_MENU_LST
        CHECK_MENU_LST_SUB

        if [[ $kernel != "" && $initrd != "" ]]; then
            initrd_current=$(echo $initramfs | awk -F "/" '{ print $NF }')

            if [[ $ACTION == "config" ]]; then

                # Update new entries for included PowerPath initramfs/initrd.
                if [[ ${VERSION} == "RHEL6" ]]; then
                    cat $MENU_LST | awk -v n=$a '/^[ \t]*title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
                                    sed -e s%${initrd_current}%${initrd}% \
                                        -e '/title/ s/(PowerPath)//' \
                                        -e s%${initrd}%${initrd_current}% \
                                        -e '/title/ s/$/(PowerPath)/'  >> $TMP_MENU_LST
                elif [[ ${VERSION} == "SLES11" ]]; then
                    cat $MENU_LST | awk -v n=$a '/^[ \t]*title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
                                    sed -e s%${initrd_current}%${initrd}% \
                                        -e '/title/ s/(PowerPath)//' \
                                        -e s%${initrd}%${initrd_current}% \
                                        -e '/title/ s/$/(PowerPath)/'  >> $TMP_MENU_LST
                fi

            elif [[ $ACTION == "remove" ]]; then

                # Update new entries for excluded PowerPath initramfs/initrd.
                if [[ ${VERSION} == "RHEL6" ]]; then
                    cat $MENU_LST | awk -v n=$a '/^[ \t]*title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
                                    sed -e s%${initrd}%${initrd_current}% \
                                        -e '/title/ s/(PowerPath)//'  >> $TMP_MENU_LST
                elif [[ ${VERSION} == "SLES11" ]]; then
                    cat $MENU_LST | awk -v n=$a '/^[ \t]*title/{++i==n && ++flag} flag; /initrd/&&flag{flag=0}' |\
                                    sed -e s%${initrd}%${initrd_current}% \
                                        -e '/title/ s/(PowerPath)//'  >> $TMP_MENU_LST
                fi

            fi

            menulstvalue=$(cat $MENU_LST | grep "^[ \t]*title" | wc -l)
            cat $TMP_MENU_LST | egrep "^[ \t]*default=[0-9]" > /dev/null 2>&1
            menulsterror1=$?

            if [ ${menulsterror1} -eq 0 ]; then
                menulstvalue_cur=$(cat $TMP_MENU_LST | grep "^[ \t]*default" |\
                                                       awk -F " |=" '{ print $NF }')
                cat $TMP_MENU_LST | sed -e "/^[ \t]*default/  \
                                    s%default=$menulstvalue_cur%default=$menulstvalue%" > $TMP1_MENU_LST
            fi

            cat $TMP_MENU_LST | egrep "^[ \t]*default [ \t]*[0-9]" > /dev/null 2>&1
            menulsterror2=$?

            if [ ${menulsterror2} -eq 0 ]; then
                menulstvalue_cur=$(cat $TMP_MENU_LST | grep "^[ \t]*default" |\
                                                       awk -F " |=" '{ print $NF }')
                cat $TMP_MENU_LST | sed -e "/^[ \t]*default/  \
                                    s%default [ \t]*$menulstvalue_cur%default $menulstvalue%" > $TMP1_MENU_LST
            fi

            countline=$(cat $TMP1_MENU_LST | wc -l)

            if [[ ${menulsterror1} == 0 || ${menulsterror2} == 0 ]]; then

               if [[ ${countline} == 0 ]]; then
                   echo "Failed"
                   STATUS="Failed:msg_menulst_update"
               else
                   cp $TMP1_MENU_LST $MENU_LST

                   if [[ $kernel != "" && $initrd != "" ]]; then
                       echo Done
                   else
                       echo "Failed"
                       STATUS="Failed:msg_menulst_update"
                   fi

               fi

           else
               echo "Failed"
               STATUS="Failed:msg_menulst_update"
           fi

        else
            echo "Failed"
            STATUS="Failed:msg_menulst_update"
        fi

    else
        echo "Failed"
        STATUS="Failed:msg_menulst_update"
    fi

}

MENULST_UPDATE_MAIN()
{

    STAGE=STAGE4
    echo -n "   Updating $MENU_LST ............ "
    MENULST_UPDATE

    if [[ ${STATUS%%:*} == Failed ]]; then
        EXIT=${STATUS##*:}
        MESSAGES $EXIT
        ROLLBACK
    fi

}

#-----------------------------------------------------
##   Miscellaneous Function 
#-----------------------------------------------------
MISC()
{

    if [[ $ACTION == "config" ]]; then

        if [[ $FORCE == "-force" && -f $TMP_PP_ADD_LUN ]]; then
            # Dynamic LUN(s) addition if dynamic LUN(s) removed
            # in previous steps.
            FC_SCAN_SUB
            powermt config
            UDEV_SETTLE
            emcpadm import_mappings -f $TMP_EMCP_MAPPING  > /dev/null 2>&1
            echo $PP_LVM_LUN | grep emcpower  > /dev/null 2>&1

            if [[ $? == 0 ]]; then
                pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                            awk -F "=" '{ print $NF }' | egrep -v ${PP_LVM_LUN} | grep -v ${PP_BOOT_LUN})
            else
                pp_pseudo_names=$(powermt display dev=all | grep emcpower |\
                            awk -F "=" '{ print $NF }' | grep -v ${PP_BOOT_LUN})
            fi

            LUN_ID $pp_pseudo_names
            echo "   Dynamic LUN(s) addition: $(echo $device_all)"
            rm -f $TMP_PP_ADD_LUN
        fi

    elif [[ $ACTION == "remove" ]]; then

        if [ -f $POWERPATH ]; then
            # Moving PowerPath startup script for PowerPath 
            # un-installation preparation.
            mv -f ${POWERPATH} ${POWERPATH}.${DATE}

            if [ $? -eq 0 ]; then
                echo "   Moving ${POWERPATH} ............ Done"
                pp_file_moved=yes 
            else
                echo "   Moving ${POWERPATH} ............ Failed"
            fi

        else 
            MESSAGES msg_pp_script
        fi

    fi

    if [[ $ACTION == "remove" || $ACTION == "upgrade" ]]; then
        # Update lvm filter for removel of r/emcpower entry.
        if [[ ${VERSION} == "RHEL6" || ${VERSION} == "SLES11" ]]; then
            cat $LVM | sed -e '/^[ \t]*filter/  {
                       s%\"r/emcpower.\*/\", \"a/sd.\*/\"%\"a/.\*/\"%g
                       }'  > $TMP_LVM
        fi
        cp $TMP_LVM $LVM
        vgscan -v  > /dev/null 2>&1
        lvmdiskscan  > /dev/null 2>&1

    fi
}

#-----------------------------------------------------
##   Check root authorization
#-----------------------------------------------------
if [[ $(whoami) != "root" ]]; then
    MESSAGES msg_insufficient_permission 
fi

#-----------------------------------------------------
##   Linux Kernels Distribution Check
#-----------------------------------------------------

if [ -f ${REDHAT} ]; then
    VERSION=RHEL$(cat ${REDHAT} \
            | sed 's/^.*release \([0-9]\)[0-9.]* .*/\1/') > /dev/null 2>&1
elif [ -f ${SLES} ]; then
    VERSION=SLES$(cat ${SLES} | awk '/^VERSION/ {version=$NF} 
                                END {print version}') > /dev/null 2>&1
fi

#-----------------------------------------------------
##   MAIN Function
#-----------------------------------------------------

case $VERSION in
RHEL6|SLES11)

    if [[ $1 == "config" ]]; then

        if [[ $2 != "" ]]; then
            if [[ $2 == "-force" ]]; then
                FORCE=$2
            else
                MESSAGES msg_incorrect_input
                USAGE
                ERROR_EXIT
            fi
        fi
        if (( $# >= 3 )); then
                MESSAGES msg_incorrect_input
                USAGE
                ERROR_EXIT
        fi

        CLEANUP
        ACTION=$1

        if [ ! -f $PP_BFS_DONE ]; then

            if [ ! -f $POWERPATH ]; then
                MESSAGES msg_pp_script1
            fi

            if [[ ${VERSION} == "RHEL6" && ! -d $PP_RHEL6_UNI_DIR ]]; then
                MESSAGES msg_pp_rhel6bfs_dir
            fi 

            MESSAGES msg_phase1
            CONFIG_CHECK 
            MESSAGES msg_phase2_${ACTION}
            trap CTRL_C SIGHUP SIGINT SIGTERM 
            LUNS_CHECK 
            FSTAB_UPDATE_MAIN 
            LVM_UPDATE_MAIN 
            INITRAMFS_CREATE_MAIN 
            MENULST_UPDATE_MAIN 
            MISC 
            touch $PP_BFS_DONE
            MESSAGES msg_config_success

        else
            MESSAGES msg_pp_bfs_configured
        fi

    elif [[ $1 == "remove" ]]; then
        if (( $# >= 2 )); then
                MESSAGES msg_incorrect_input
                USAGE
                ERROR_EXIT
        fi

        CLEANUP
        ACTION=$1

        if [ -f $PP_BFS_DONE ]; then
            MESSAGES msg_phase1
            CONFIG_CHECK 
            MESSAGES msg_phase2_${ACTION}
            trap CTRL_C SIGHUP SIGINT SIGTERM 
            FSTAB_UPDATE_MAIN 
            LVM_UPDATE_MAIN 
            INITRAMFS_CREATE_MAIN 
            MENULST_UPDATE_MAIN 
            MISC 
            rm -f $PP_BFS_DONE
            MESSAGES msg_remove_success
        else
            MESSAGES msg_pp_bfs_not_configured
        fi

    elif [[ $1 == "upgrade" ]]; then
          if (( $# >= 2 )); then
                MESSAGES msg_incorrect_input
                USAGE
                ERROR_EXIT
          fi
          CLEANUP
          ACTION=$1

          if [ -f $PP_BFS_DONE ]; then
              MESSAGES msg_phase1
              CONFIG_CHECK
              MESSAGES msg_phase2_${ACTION}
              trap CTRL_C SIGHUP SIGINT SIGTERM 
              FSTAB_UPDATE_MAIN 
              LVM_UPDATE_MAIN 
              MISC 
              rm -f $PP_BFS_DONE
              MESSAGES msg_upgrade_success
          else
              MESSAGES msg_pp_bfs_not_configured
          fi

    elif [[ $1 == "help" ]]; then
        USAGE

    else
        USAGE
    fi

;;
*)
    MESSAGES msg_not_supported_kernel
;;
esac
