#!/bin/bash 

#
# Script to configure PowerPath into initramfs image.
#

################################################################################
### Import platform specific pre spec definitions here.
# Redhat x86_64 specific:
#
# Install only if this is a Redhat, x86_64 system
#

case "$VENDOR" in
    redhat)
        EXPECTED_VENDOR=redhat
        VENDOR_NAME=RedHat
        VENDOR_OS_NAME=RHEL6
        EXPECTED_OS_REV=6
        ;;
    asianux)
        EXPECTED_VENDOR=asianux
        VENDOR_NAME=Asianux
        VENDOR_OS_NAME=Asianux-4.0
        EXPECTED_OS_REV=4
        ;;
    *)
        VENDOR_NAME="Redhat or Asianux"
esac

EXPECTED_ISA=x86_64
MIN_UPGRADE_REV=5.0.0
MIN_NDU_UPGRADE_REV=6.5.0

check_vendor_rev()
{
local rhel_version

case  "$VENDOR" in
    redhat)
        rhel_version=`sed '/^[ \t]*#/d;s/^.*release \([0-9]\)[0-9.]* .*/\1/' \
                                                        /etc/redhat-release`
        ;;
    asianux)
        rhel_version=`sed '/^[ \t]*#/d;s/^.*Server \([0-9]\)[0-9.]* .*/\1/' \
                                                        /etc/asianux-release`
        ;;
esac

if [ "$1" = "$rhel_version" ] ; then
       /bin/true
else 
       /bin/false
fi
}

#-----------------------------------------------------------------------
# identify_platform -
# Determine the set of drivers files compatible with the /lib/modules
# subdirectory passed as an argument and echo the tag for that set of
# drivers to stdout.
#-----------------------------------------------------------------------

identify_platform()
{
    local platform=

    #
    # Recognize production or custom RHEL kernel
    #
    platform=`echo $1 | \
    gawk -v V=rhel6 -v M=_x8664 \
        '/2.6.[0-9.-]+((el6)|(AX))/      {print V M; exit 0}
          {exit 1}'`

    if [ $? -ne 0 ]
    then
        if [ "$1" = `uname -r` ]; then
            pre_error "This PowerPath package does not support this kernel."
            cleanup_error_exit
        fi
    fi


    if [ "$platform" ] ; then
         echo "$platform"
    fi
}
################################################################################

pp_version=`cat /etc/opt/emcpower/.pp_version`
pp_install_dir=/etc/opt/emcpower/EMCpower.LINUX-${pp_version}

cleanup_error_exit()
{
    exit 1
}

pre_error()
{
    echo $*
}
    
copy_mod()
{
    copy_file "$1" "$2" && chmod 644 "$2" && chown root:root "$2"
}

#
# On kernel upgrade, a new initramfs would be created automatically.
# But if BFS is configured already, when building the new intiramfs,
# PP modules will also tried to be included in it.  Since powerpath
# modules are not yet loaded into the new default modules folder,
# /lib/modules/<new kernel version>/,  the newly built initramfs
# will not have powerpath modules and on kernel reboot, the host will
# fail to load.  Hence copy the powerpath modules to the new kernel
# modules folder.
#
if test "`cat $pp_install_dir/../.os_version`" != "$kernel"
then
    MODULE_BASE=/lib/modules/$kernel

    TAG=`identify_platform $kernel`
    if [ -z "$TAG" ]; then
        echo "The installed PowerPath package does not support the upgraded kernel."
        exit 1
    fi

    for os in /lib/modules/*
    do
        case $os in
            /lib/modules/`uname -r`)
                for modpath in $os/powerpath/*
                do
                    rm -f $modpath
                done
                rm -rf $os/powerpath
                ;;
            *)
                rm -rf $os/powerpath
                ;;
        esac
        for modpath in $os/extra/emcp*
        do
            rm -f $modpath
        done
    done

    mkdir -p $MODULE_BASE/powerpath 2>/dev/null

    for mod in `ls $pp_install_dir/bin/driver/$TAG`
    do
        cp -pf $pp_install_dir/bin/driver/$TAG/$mod $MODULE_BASE/powerpath/$mod
    done

    depmod

    echo $kernel > $pp_install_dir/../.os_version
fi

# On RHEL6/OL6 (that use dracut), specify the powerpath.conf file with only
# the array of the root device being managed.  Otherwise all the array classes
# will be managed and during /etc/init.d/PowerPath start, any of the classes
# that may be 'unmanaged' by the user cannot be unmanaged.  Hence specify only
# the root dev array class as managed so that PP starts with only that array
# as managed while initramfs loads.  Then during /etc/init.d/PowerPath start,
# the manage/unmanage settings of other classes will be set through
# powermt init boot.

TMP_MODP=/tmp/powerpath.conf
PP_MODP=/etc/modprobe.d/powerpath.conf

ROOT_VG=`mount 2>/dev/null | grep "on / " | grep mapper | sed -e 's/^\/dev\/mapper\/\(.*\) on.*/\1/'`

if [ "$ROOT_VG" == "" ]
then
    exit 1
fi

# If a snapshot of the root logical volume exists, then dmsetup table will
# give details of the dm device.  Hence add the prefix '-real' to the name
# so that dmsetup table will give the details of the original pseudo device.
if dmsetup table $ROOT_VG | grep -q "snapshot-origin"; then
    ROOT_VG="${ROOT_VG}-real"
fi

COUNT_DEV=0

# Find the pseudo device names and device classes for the boot luns in ROOT_VG
# Pseudo device names are filled in DEV_NAME_PSEUDO[], device classes in DEV_CLASS[]
while read line
do
    DEV_MAJOR=`echo $line | sed -e 's/.* \([0-9]*\):\([0-9]*\).*/\1/'`
    DEV_MINOR=`echo $line | sed -e 's/.* \([0-9]*\):\([0-9]*\).*/\2/'`
    DEV_NAME_FULL[$COUNT_DEV]=`grep -e "^ \+$DEV_MAJOR \+ $DEV_MINOR \+" /proc/partitions | sed -e 's/^ *[0-9]* *[0-9]* *[0-9]* *//'`
    DEV_NAME[$COUNT_DEV]=`echo ${DEV_NAME_FULL[$COUNT_DEV]} | sed -e 's/[0-9]*//g'`
    DEV_NAME_PSEUDO[$COUNT_DEV]=`powermt display dev=${DEV_NAME[$COUNT_DEV]} 2>/dev/null| grep -e "Pseudo name" | sed -e 's/^Pseudo name=\(.*\)/\1/'`
    DEV_CLASS[$COUNT_DEV]=`powermt display dev=${DEV_NAME[$COUNT_DEV]} 2>/dev/null| grep -e "ID=" | grep -v "Logical" | sed -e 's/^\(.*\) ID=.*/\1/'`
    
    if [ -z ${DEV_CLASS[$COUNT_DEV]} ]; then
        exit 1
    fi 

    #Prepare a list of classes
    case "${DEV_CLASS[$COUNT_DEV]}" in
        Symmetrix)
            LAM_NAME=symm
            ;;
        CLARiiON)
            LAM_NAME=clariion
            ;;
        "HP xp")
            LAM_NAME=hpxp
            ;;
        Hitachi)
            LAM_NAME=Hitachi
            ;;
        Ess)
            LAM_NAME=ess
            ;;
        Invista)
            LAM_NAME=invista
            ;;
        VPLEX)
            LAM_NAME=vplex
            ;;
        VNX)
            LAM_NAME=vnx
            ;;
        Unity)
            LAM_NAME=unity
            ;;
        NetApp)
            LAM_NAME=netapp
            ;;
        XtremIO)
            LAM_NAME=xtremio
            ;;
        "HP HSx")
            LAM_NAME=hphsx
            ;;
        Generic)
            LAM_NAME=Generic
            ;;
        SC)
            LAM_NAME=sc
            ;;
    esac

    if [ "$LAM_NAME" == "Generic" ]
    then
        generic_lam_present=true
    else
        if [ "$COUNT_DEV" -eq 0 ]
        then
            # Initialise with first LAM_NAME
            lam_list="$LAM_NAME"
        else
            # Check if the LAM_NAME already exist in the list then skip
            if echo "$lam_list" | grep -q "$LAM_NAME"; then
                :
            else
                # Append LAM_NAME in lam_list
                lam_list="$lam_list,$LAM_NAME"
            fi
        fi
    fi

    COUNT_DEV=$((COUNT_DEV + 1))

done < <(dmsetup table $ROOT_VG 2>/dev/null)

if [ "$generic_lam_present" = true ]
then
    cat $PP_MODP | sed -e "s/^.*genericclass=\(.*\)/options emcp genericclass=\1/" > $TMP_MODP
fi

cat $PP_MODP | sed -e "s/^options emcp managedclass=.*/options emcp managedclass=$lam_list/" > $TMP_MODP

# Install the BFS powerpath.conf file in a non-standard location since
# dracut itself copies /etc/modprobe.d/powerpath.conf file to the initrd
# staging area, but would not allow it to be overwritten again.
inst_simple $TMP_MODP /etc/opt/emcpower/powerpath.conf
unlink $TMP_MODP


inst_hook pre-trigger 02 "${moddir}/emcp_pre-trigger.sh"
inst_simple "${moddir}/emcp_settled.sh"     /etc/opt/emcpower/emcp_settled.sh 

inst /bin/fgrep
inst /bin/awk
inst /bin/echo 
inst /sbin/lsmod
inst /sbin/modprobe

inst /sbin/pp_inq
inst /etc/opt/emcpower/emcpmgr /etc/opt/emcpower/emcpmgr

inst_rules  /etc/udev/rules.d/05-udev-pp.rules
inst_simple /lib/udev/pp_udev.sh

#
# Create the database for pseudo device corresponding to the boot LUN.
# emcpmgr create_db command is used for creation of boot LUN database in
# in /etc/opt/emcpower/.tmp directory.
#

dbbakdir=/etc/opt/emcpower/.tmp
# Create /etc/opt/emcpower/.tmp if it doesnt exist
if [ ! -d ${dbbakdir} ]; then
    mkdir -p ${dbbakdir}
    if [ $? -ne 0 ]; then 
        echo "Unable to create directory $dbbakdir for database"
        exit 1
    fi
else
    rm -f ${dbbakdir}/emcp_devicesDB.idx > /dev/null 2>&1
    rm -f ${dbbakdir}/emcp_devicesDB.dat > /dev/null 2>&1
fi

loop_db=0
# Create the boot LUN database
while [ $loop_db -lt $COUNT_DEV ]
do
    # In case the root volume group is present on multiple partitions
    # on the same boot disk(s),the DEV_NAME_PSEUDO array will contain 
    # duplicate entries.  But don't add the duplicate entries to the db.
    
    inner_loop=0
    add_device=1
    while [ $inner_loop -lt $loop_db ]
    do
        if [ ${DEV_NAME_PSEUDO[$loop_db]} == ${DEV_NAME_PSEUDO[$inner_loop]} ]
        then
            add_device=0
        fi
        inner_loop=$((inner_loop + 1))
    done
    if [ $add_device -eq 1 ]
    then
        /etc/opt/emcpower/emcpmgr create_db ${DEV_NAME_PSEUDO[$loop_db]} ${dbbakdir}
        if [ $? -ne 0 ]; then
            echo "emcpmgr create_db command failed for ${DEV_NAME_PSEUDO[$loop_db]}"
            exit 1
        fi
    fi
    loop_db=$((loop_db + 1))
done


# Check if ${dbbakdir}/emcp_devicesDB.idx|.dat are created
if [ ! -f ${dbbakdir}/emcp_devicesDB.idx ]; then
    echo "${dbbakdir}/emcp_devicesDB.idx not present"
    exit 1
fi

if [ ! -f ${dbbakdir}/emcp_devicesDB.dat ]; then
    echo "${dbbakdir}/emcp_devicesDB.dat not present"
    exit 1
fi

# Copy the boot LUN database files 
inst_simple ${dbbakdir}/emcp_devicesDB.idx /etc/emcp_devicesDB.idx
inst_simple ${dbbakdir}/emcp_devicesDB.dat /etc/emcp_devicesDB.dat

# Remove the newly created database files
rm ${dbbakdir}/emcp_devicesDB.idx > /dev/null 2>&1
rm ${dbbakdir}/emcp_devicesDB.dat > /dev/null 2>&1

inst_simple /etc/opt/emcpower/.pp_version 

for i in $(ls ${pp_install_dir}/bin/.drivers_*  2>/dev/null); 
do
    inst_simple ${i}
done

for mods in $(ls /lib/modules/$kernel/powerpath/*.ko 2>/dev/null);
do
    inst ${mods}
done

# OPT 441242: During early boot when Powerpath modules are loaded,
# the hostname is not set in the kernel and set to (none) by default.
# Since MpxReserveKey is dependent on hostname, in a cluster setup
# on BFS all nodes would end up with the same MpxReserveKey.
# To address this, save the current hostname into initramfs
# which can be accessed during early boot stage.
if [ -f /etc/opt/emcpower/hostname.pp ]; then
    rm /etc/opt/emcpower/hostname.pp
fi

cat /proc/sys/kernel/hostname > /etc/opt/emcpower/hostname.pp
inst_simple /etc/opt/emcpower/hostname.pp

