#!/bin/sh
#
#  Copyright (c) 2008-2012, EMC Corporation.  All Rights Reserved.
#
#  enable.sh
#
#  Enable a newly installed PowerPath package to run or enable an
#  existing package to run after a kernel upgrade.
#

#---------------------------------------
# Begin declaration of global variables.
#---------------------------------------

########
### DO NOT REMOVE THE FOLLOWING LINE
#####################################################################
### Start of Global variable section.
#####################################################################

# Temp directory used by the %pre section.  (Before $PP_I_DIR exists.)
#
PRE_TMP=/var/tmp
#
# Default installation directory for emcpower
#
PP_I_DIR=/etc/opt/emcpower
#
# The file name of the device file used to control the power path drivers
#
# created by sysfs in 2.6.
#POWER_DEV=/dev/emcpower
#
# Installation log file and log.1 (n-1)
#
POWER_LOG=$PP_I_DIR/log
POWER_LOG_N1=$PP_I_DIR/log.1
#
# Installation temporary file directory.
#
POWER_TMP_DIR=$PP_I_DIR/.tmp
#
# Backup archives used in case an installation is aborted in mid-stream
#
POWER_BACKUP_ARCHIVE=$PP_I_DIR/.archive.tar
POWER_BACKUP_ARCHIVE_NEW=$PP_I_DIR/.archive_NEW.tar
archive_dir=$RPM_INSTALL_PREFIX/etc/emc/archive
#
# Patch log file in case of patch errors and log.1 (n-1)
#
PATCH_LOG=$PP_I_DIR/patch.log
PATCH_LOG_N1=$PP_I_DIR/patch.log.1
#
# Check platform compatibility for installing D@RE components
# Set INCLUDE_DARE to 1 if the platform is supported.
#
INCLUDE_DARE=0
if [ -f /etc/ovs-release ]
then
    host_os=`sed 's/^.*release \([0-9]\)[0-9.]*/\1/' \
                                           /etc/ovs-release`
    host_os_name=OVS${host_os}
elif [ -f /etc/oracle-release ]
then
    host_os=`sed 's/^.*release \([0-9]\)[0-9.]*/\1/' \
                                           /etc/oracle-release`
    host_os_name=OL${host_os}
elif [ -f /etc/SuSE-release ]
then
    host_os=`awk '/VERSION/ {version=$3}
                  END { print version }' /etc/SuSE-release`
    host_os_name=SLES${host_os}
    host_os_patchlevel=`awk '/PATCHLEVEL/ {patchlevel=$3}
                  END { print patchlevel }' /etc/SuSE-release`
elif [ -f /etc/redhat-release ]
then
    citrix_release=`grep "XenServer release" /etc/redhat-release`
    if [ -n "$citrix_release" ]
    then
        host_os="6"
        host_os_name=CXS${host_os}
    else
        host_os=`sed 's/^.*release \([0-9]\)[0-9.]* .*/\1/' \
                                               /etc/redhat-release`
        host_os_name=RHEL${host_os}
    fi
elif [ -f /etc/asianux-release ]
then
    host_os=`sed 's/^Asianux [a-zA-Z]* \([0-9]\)[0-9.]* .*/\1/' \
                                           /etc/asianux-release`
    host_os_name=Asianux-${host_os}
fi

# DARE is now supported on x86_64 version of RHEL5 & SLES10
if [ "$host_os_name" = "RHEL5" ]; then
    if [ "`uname -m`" = "x86_64" ]; then
        INCLUDE_DARE=1
    fi
fi
if [ "$host_os_name" = "RHEL6" ]; then
    if [ "`uname -m`" = "x86_64" ]; then
        INCLUDE_DARE=1
    fi
fi
if [ "$host_os_name" = "SLES10" ]; then
    if [ "`uname -m`" = "x86_64" ]; then
        INCLUDE_DARE=1
    fi
fi
if [ "$host_os_name" = "SLES11" ]; then
    if [ "$host_os_patchlevel" = "2" ]; then
        if [ "`uname -m`" = "x86_64" ]; then
            INCLUDE_DARE=1
        fi
    fi
fi

INCLUDE_OPEN_FCOE=0
if [ -f ${RPM_INSTALL_PREFIX}${PP_I_DIR}/EMCpower.LINUX-%version/PowerFcoe ]; then 
    INCLUDE_OPEN_FCOE=1
fi

INCLUDE_04_POWERISCSI=0
if [ -f ${RPM_INSTALL_PREFIX}${PP_I_DIR}/EMCpower.LINUX-%version/04-poweriscsi ]; then 
    INCLUDE_04_POWERISCSI=1
fi

INCLUDE_DRACUT_CONFIG=0
if [ -d ${RPM_INSTALL_PREFIX}${PP_I_DIR}/EMCpower.LINUX-%version/90powerpath ]; then
    INCLUDE_DRACUT_CONFIG=1
fi

INCLUDE_EMCPBFS_LINUX=0
if [ -f ${RPM_INSTALL_PREFIX}${PP_I_DIR}/EMCpower.LINUX-%version/emcpbfs_linux ]; then
    INCLUDE_EMCPBFS_LINUX=1
fi

INCLUDE_PP_RESET_DM_DEPS_SCRIPT=0
if [ -f ${RPM_INSTALL_PREFIX}${PP_I_DIR}/EMCpower.LINUX-%version/pp_reset_dm_deps.sh ]; then
    INCLUDE_PP_RESET_DM_DEPS_SCRIPT=1
fi


#
# local modprobe file
if [ "$host_os_name" = "RHEL6" -o "$host_os_name" = "OL6" -o \
     "$host_os_name" = "CXS6" ]; then
    modprobe_file=/etc/modprobe.d/powerpath.conf
else
    modprobe_file=/etc/modprobe.conf.pp
fi

# Check platform compatibility for installing PPME components
# Set INCLUDE_PPME to 0 only if the platform is not supported
#
INCLUDE_PPME=1
#No Support for PPME
if [ "$host_os_name" = "OVS3" -o "$host_os_name" = "CXS6" ]; then
    INCLUDE_PPME=0
fi

#####################################################################
### End of Global variable section.
#####################################################################
########

PATH=/sbin:/bin:$PP_I_DIR/bin; export PATH

RHEL6_HOST=no
RHEL55_HOST=no
OL6_HOST=no
CXS6_HOST=no

TMP_MODP=/tmp/modprobe.conf.pp
PP_MODP=/etc/modprobe.conf.pp

cmd_path=`echo $0 | sed 's:/[^/][^/]*$::'`
PPBASE=`(cd $cmd_path;pwd)`

test -f $PP_I_DIR/.pp_version && PP_VERSION=`cat $PP_I_DIR/.pp_version`
test -f $PP_I_DIR/.new_pp_version && \
                          NEW_PP_VERSION=`cat $PP_I_DIR/.new_pp_version`
test -f $PP_I_DIR/.os_version && OS_VERSION=`cat $PP_I_DIR/.os_version`

if [ -f /etc/oracle-release ]
then
VENDOR=oracle
oracle_version=`sed 's/^.*release \([0-9]\)[0-9.]*/\1/' \
                                        /etc/oracle-release`

oracle_update=`sed 's/^.*release [0-9]\([.0-9]\)*.*/\1/' \
                                        /etc/oracle-release`


if [ "${oracle_version}" == "6" ]; then
    OL6_HOST=yes
    TMP_MODP=/tmp/powerpath.conf
    PP_MODP=/etc/modprobe.d/powerpath.conf
fi
elif [ -f /etc/SuSE-release ]
then
    VENDOR=suse
elif [ -f /etc/asianux-release ]
then
    VENDOR=asianux
elif [ -f /etc/redhat-release ]
then
    citrix_release=`grep "XenServer release" /etc/redhat-release`
    if [ -n "$citrix_release" ]
    then
        VENDOR=citrix
        CXS6_HOST=yes
        TMP_MODP=/tmp/powerpath.conf
        PP_MODP=/etc/modprobe.d/powerpath.conf
    else
        VENDOR=redhat

        rhel_version=`sed 's/^.*release \([0-9]\)[0-9.]* .*/\1/' \
                                            /etc/redhat-release`

        rhel_update=`sed 's/^.*release [0-9]\([.0-9]\)* .*/\1/' \
                                            /etc/redhat-release`

        if [ "${rhel_version}" == "6" ]; then
            RHEL6_HOST=yes
            TMP_MODP=/tmp/powerpath.conf
            PP_MODP=/etc/modprobe.d/powerpath.conf
        elif [ "${rhel_version}" == "5" ]; then
            if [ -n "${rhel_update}" ] && [ ${rhel_update} -ge 5 ]; then
                RHEL55_HOST=yes
            fi
        fi
    fi

fi

#---------------------------------------
# End declaration of global variables.
#---------------------------------------

init_I18N()
{
    type -P gettext.sh > /dev/null 2>&1 && \
        type -p gettext >/dev/null  2>&1

    if [ $? -ne 0 ]; then
        gettext()
        {
            echo "$*"
        }
        eval_gettext()
        {
            eval "echo \"$*\""
        }
    else
        . gettext.sh

        TEXTDOMAIN=EMCpower
        export TEXTDOMAIN
        TEXTDOMAINDIR=$PPBASE/i18n/catalog
        export TEXTDOMAINDIR
        export RPM_INSTALL_PREFIX
    fi
}

report_error()
{
    (eval_gettext "$*"
     echo ) 1>&2
}

error_exit()
{
    exit 1
}

#-----------------------------------------------------------------------
# Restore system to the state that existed before this script ran.
# First, execute the commands in the undo list in reverse order, then
# untar archived files.
#-----------------------------------------------------------------------
rollback()
{
    awk '{print NR,$0}' $POWER_TMP_DIR/undolist | \
        sort -nr | \
        sed 's/[^ ][^ ]* //' > $POWER_TMP_DIR/undo.sh
    sh $POWER_TMP_DIR/undo.sh

    if [ -f $POWER_TMP_DIR/rollbackfiles.tar ]; then
        tar -x --absolute-names --file $POWER_TMP_DIR/rollbackfiles.tar
    fi
}

#-----------------------------------------------------------------------
# Delete the files containing rollback information
#-----------------------------------------------------------------------
rollback_reset()
{
    rm -f $POWER_TMP_DIR/rollbackfiles.tar
    rm -f $POWER_TMP_DIR/undolist
    rm -f $POWER_TMP_DIR/undo.sh
}

#-----------------------------------------------------------------------
# Save a directory and contained files in the rollback archive
#-----------------------------------------------------------------------
save_dirtree_for_rollback()
{
    local pathname
    case "$1" in
        /*) pathname=$1 ;;
         *) pathname=`pwd`/$1 
    esac
   tar --append --preserve-permissions --absolute-names \
       --file $POWER_TMP_DIR/rollbackfiles.tar $pathname
}

#-----------------------------------------------------------------------
# Save a file or directory in the rollback archive
#-----------------------------------------------------------------------
save_for_rollback()
{
    local pathname
    case "$1" in
        /*) pathname=$1 ;;
         *) pathname=`pwd`/$1 
    esac
    tar --append --preserve-permissions --absolute-names \
    --no-recursion --file $POWER_TMP_DIR/rollbackfiles.tar $pathname
}

#-----------------------------------------------------------------------
# Add a shell command, for execution during rollback, to the undo list
#-----------------------------------------------------------------------
add_to_undolist()
{
    echo "cd `pwd`; $*" >> $POWER_TMP_DIR/undolist
}

#-----------------------------------------------------------------------
# Move a file in such a way that the original source and destination
# files are restored by rollback.
#-----------------------------------------------------------------------
move_file()
{
    save_for_rollback $1
    local dest
    if [ -d "$2" ]; then
        dest=$2/`basename $1`
    else
        dest=$2
    fi
    if [ -f "$dest" ]; then
        save_for_rollback $dest
    else
        add_to_undolist rm -f "$dest"
    fi
    mv -f $1 $dest
}

#-----------------------------------------------------------------------
# Copy a new file over an old one,in such a way that the old file
# can be restored during rollback. 
#-----------------------------------------------------------------------
copy_file()
{
    local dest
    if [ -d "$2" ]; then
        dest=$2/`basename $1`
    else
        dest=$2
    fi
    if [ -f "$dest" ]; then
        save_for_rollback $dest
    else
        add_to_undolist rm -f "$dest"
    fi
    cp -pf $1 $2
}

#-----------------------------------------------------------------------
# Save a file in the rollback archive and then delete it.
#-----------------------------------------------------------------------
remove_file()
{
    if [ -f "$1" ]; then
        save_for_rollback $1
        rm -f $1
    fi
}

#-----------------------------------------------------------------------
# Save a directory and contained files in the rollback archive and then
# delete them.
#-----------------------------------------------------------------------
remove_dirtree()
{
    if [ -d "$1" ]; then
        save_dirtree_for_rollback $1
        rm -rf $1
    fi
}

#-----------------------------------------------------------------------
# Make a directory in such a way that it will be removed during rollback.
# All non-existent directories in the given path are created.  If the
# directory already exists, do nothing.
#-----------------------------------------------------------------------
make_dir()
{
    local path
    local newdir
    set -- `echo $1 | sed 's:/:/ :g'`
    for dir 
    do
        path="${path}${dir}"
        if [ ! -d $path ]
        then
           add_to_undolist rmdir $path
           mkdir $path
           newdir=T
        fi
    done
    [ "$newdir" ] && chmod 755 $path && chown root:root $path
}

#-----------------------------------------------------------------------
# Copy a kernel module and set file pwermissions, group and owner
#-----------------------------------------------------------------------
copy_mod()
{
    copy_file "$1" "$2" && chmod 644 "$2" && chown root:root "$2"
}

#-----------------------------------------------------------------------
# Compare the vermagic string of the pp base driver to the vermagic string
# of the scsi_mod driver.
# input: path to PowerPath base driver, in package area.
# return 0 for matching strings.
#-----------------------------------------------------------------------

verify_driver_vermagic()
{
    local pp_drv_path=$1
    local ref_driver
    local ref_mod_version
    local pp_mod_version

    ref_driver=`lsmod | sed -n -e 's/ .*//' -e '$p'`
    ref_mod_version=`modinfo $ref_driver | \
        sed -n '/^vermagic:/s/^vermagic:  *//p'`
    pp_mod_version=`modinfo $pp_drv_path | \
        sed -n '/^vermagic:/s/^vermagic:  *//p'`
    ref_mod_version=`echo $ref_mod_version | sed -e 's/^[^ ]* //'`
    pp_mod_version=`echo $pp_mod_version | sed -e 's/^[^ ]* //'`
    if [ "$pp_mod_version" = "$ref_mod_version" ]
    then
        true
    else
        false
    fi
}

#-----------------------------------------------------------------------
# Recursively load all modules on the command line, in the order given.
# If any module fails to load, all previously loaded modules are unloaded
# and a non-zero status is returned.  After all modules are loaded, emcpioc
# is unloaded.
#-----------------------------------------------------------------------

load_all_modules()
{
    local mod=`basename "$1" .ko`
    shift 1

    if [ -z "$mod" ]
    then
        if lsmod | grep emcpioc > /dev/null
        then
            modprobe -r emcpioc
        fi
        return 0
    fi
    if [ $mod == "emcp" ]; then
       klh=`fgrep -w kallsyms_lookup_name /proc/kallsyms \
       | awk '{ print $1 }' \
       | awk 'a !~ $0; {a=$0}'`

       if [ "$RHEL55_HOST" == "yes" ]; then
           failfastflag="osfailfast=0x1"
       else
           failfastflag="osfailfast=0x0"
       fi

       emcpo=`cat $PP_MODP | grep -w "options emcp"`
       cat $PP_MODP | grep -v -w "options emcp" > $TMP_MODP

       if [ "$emcpo" == "" ]; then
           # no entry yet in powerpath.conf
           echo "options emcp emcplu=0x$klh $failfastflag" >> $TMP_MODP
       else
           # some emcp options entry found
           oline=`cat $PP_MODP | grep -w "options emcp" \
            | sed -s 's/emcplu=0x[a-f0-9]*//' \
            | sed -s 's/osfailfast=0x[0-9]*//'`
           echo "$oline emcplu=0x${klh} $failfastflag" >> $TMP_MODP
       fi
       mv -f $TMP_MODP $PP_MODP
    fi
    if modprobe -q $mod
    then
        load_all_modules $*
        if [ $? -ne 0 ]
        then
            modprobe -r $mod
            return 1
        fi
    else
        report_error 'PowerPath could not load module $mod'
        return 1
    fi
}

#-----------------------------------------------------------------------
# Run "preinstall" checks to make sure the running system is compatible
# with this package.
#-----------------------------------------------------------------------
validate_install_target()
{
## Check - Require effective UID of root

    if [ $EUID != 0 ]; then
        report_error "You must be root to install PowerPath."
        error_exit
    fi

## Check - Only install on a 2.6 or a 3.0 kernel

    uname -r | grep '2\.6\|3\.0' > /dev/null
    if [ $? -ne 0 ]; then
        report_error "This PowerPath package does not support this kernel."
        error_exit
    fi

## Check vendor

    if [ "$EXPECTED_VENDOR" != "$VENDOR" ]; then
        report_error 'This package requires a $VENDOR_NAME Platform.'
#        report_error 'This package requires a $VENDOR_NAME BUT GOT -$VENDOR- Platform.'
        error_exit
    fi

## Check vendor rev.

    check_vendor_rev $EXPECTED_OS_REV
    if [ $? != 0 ]; then
        report_error 'This package requires $VENDOR_NAME $VENDOR_OS_NAME.'
        error_exit
    fi

## Check hardware platform

    if [ "`uname -m`" != "$EXPECTED_ISA" ]; then
        report_error \
            'This package requires the $VENDOR_NAME $EXPECTED_ISA kernel.'
        error_exit
    fi

## Check - Make sure no devices are in use.

    if [ "`/sbin/lsmod | grep -w emcp`" != "" ]; then
        /sbin/powermt save > /dev/null 2>&1
        /sbin/powermt remove dev=all > /dev/null 2>&1
        if [ "`powermt display dev=all 2>&1 | grep "not found"`" = "" ]; then
            report_error \
                "Unable to remove devices from the PowerPath configuration."
            report_error \
                "Please make sure no PowerPath devices are in use and retry."
            /sbin/powermt config > /dev/null 2>&1
            /sbin/powermt load > /dev/null 2>&1
            error_exit
        fi
        /sbin/powermt config > /dev/null 2>&1
        /sbin/powermt load > /dev/null 2>&1
    fi

## Do we have modules that work with this kernel?

    TAG=`identify_platform \`uname -r\``
    if [ -z "$TAG" ]; then
        report_error "This PowerPath package does not support this kernel."
        report_error '$PPBASE'
        error_exit
    fi

## Check driver vermagic

    verify_driver_vermagic $PPBASE/bin/driver/$TAG/emcp.ko
    if [ $? != 0 ]; then
        report_error 'PowerPath driver version magic mismatch'
        error_exit
    fi
}

#-----------------------------------------------------------------------
# Compare the version recorded in the saved powermt.custom file with the
# version in $1.  (The version in the saved powermt.custom file is in the
# third colon delimited field of the first line.)  If the two versions
# match, return true.
#-----------------------------------------------------------------------
matching_saved_config_version()
{
    local saved
    local Mmp

    if [ -f $archive_dir/powermt_custom.xml.saved ]; then
        Mmp=`echo "$1" | \
            grep '^\([0-9]\.[0-9]\.[0-9]\.[0-9][0-9]\.[0-9][0-9]\)' | \
            sed 's/0\([0-9]\)/\1/g'`

        archivedFile=$archive_dir/powermt_custom.xml.saved
        major=`cat $archivedFile | grep "<major>" | \
            sed 's/<major>\([0-9]*\)<\/major>/\1/'`
        minor=`cat $archivedFile | grep "<minor>" | \
            sed 's/<minor>\([0-9]*\)<\/minor>/\1/'`
        patch=`cat $archivedFile | grep "<patch>" | \
            sed 's/<patch>\([0-9]*\)<\/patch>/\1/'`
        servicePack=`cat $archivedFile | grep "<servicePack>" | \
            sed 's/<servicePack>\([0-9]*\)<\/servicePack>/\1/'`
        hotfix=`cat $archivedFile | grep "<hotfix>" | \
            sed 's/<hotfix>\([0-9]*\)<\/hotfix>/\1/'`

        saved="$major.$minor.$servicePack.$patch.$hotfix"
        saved=`echo $saved| sed 's/ //g'`

        if [ "$saved" = "$Mmp" ]; then
            /bin/true
        else
            /bin/false
        fi
    elif [ -f $archive_dir/powermt.custom.saved ]; then
        Mmp=`echo "$1" | \
            grep '^\([0-9]\.[0-9]\.[0-9]\.[0-9][0-9]\.[0-9][0-9]\)' | \
            sed 's/0\([0-9]\)/\1/g'`
        saved=`sed -n -e 's/[^:][^:]*:[^:][^:]*:\([^:][^:]*\).*/\1/' -e 1p \
            $archive_dir/powermt.custom.saved`
        if [ "$saved" = "$Mmp" ]; then
            /bin/true
        else
            /bin/false
        fi
    else
        /bin/false
    fi
}

#-----------------------------------------------------------------------
# Move files from the PowerPath archive directory to their normal
# installed locations.
# In case of the custom file, the mpapi-based powermt saves the 
# configuration in XML format. Therefore copy the xml file to the 
# normal location. In order to support upgrade from an older PP
# version (where XML formt is not supported), the old style custom
# file should be considered.
#-----------------------------------------------------------------------
restore_configuration_files()
{
    for file in /etc/emc/mpaa.lams \
        /etc/emc/mpaa.excluded 
    do
      if [ -f $archive_dir/`basename $file`.saved ]; then
          move_file $archive_dir/`basename $file`.saved $file
      fi
    done

    if test "$PP_VERSION" || \
                matching_saved_config_version $NEW_PP_VERSION; then
        if [ -f $archive_dir/powermt_custom.xml.saved ] ; then
            move_file $archive_dir/powermt_custom.xml.saved \
                    /etc/powermt_custom.xml
        elif [ -f $archive_dir/powermt.custom.saved ]; then
            move_file $archive_dir/powermt.custom.saved /etc/powermt.custom
        fi

        for file in /etc/emcp_devicesDB.dat \
            /etc/emcp_devicesDB.idx
        do
          if [ -f $archive_dir/`basename $file`.saved ]; then
              move_file $archive_dir/`basename $file`.saved $file
          fi
        done

        for file in $archive_dir/*.FCS
        do
            if [ -f $file ]; then
                move_file $file /etc
            fi
        done
    fi
}

#-----------------------------------------------------------------------
# tps_managed_classes - Return a true status if third party software
# is installed to manage the array named in $1.  Otherwise return a
# false status.
#-----------------------------------------------------------------------
tps_managed()
{
case "$1" in
    hitachi)
        test -d /opt/DynamicLinkManager/bin
        ;;
    hpxp)
        test -d /usr/src/Autopath
        ;;
    ess)
        test -d /opt/IBMsdd/bin
        ;;
    *)
        /bin/false
        ;;
esac
}

#-----------------------------------------------------------------------
# prev_unmanaged - Return a true status if the array named in $2
# is marked "unmanaged" in the mpaa.lams file named in $1
#-----------------------------------------------------------------------
prev_unmanaged()
{
  grep -w $2 $1 2>/dev/null | grep -w unmanaged > /dev/null 2>&1
}

#-----------------------------------------------------------------------
# prev_managed - Return a true status if the array named in $2
# is marked "managed" in the mpaa.lams file named in $1
#-----------------------------------------------------------------------
prev_managed()
{
  grep -w $2 $1 2>/dev/null | grep -w managed > /dev/null 2>&1
}
#-----------------------------------------------------------------------
# file_compare - Compare the contents of two files.  This function is used
# because /usr/bin/diff may be unavailable.
#
# $1, $2 - Files to compare
#
# Return status
#  0 ==> The file are the same.
#  1 ==> The file are different.
#-----------------------------------------------------------------------
file_compare()
{
    file1_lines=`grep -c '.*' $1`
    file2_lines=`grep -c '.*' $2`
    if [ $file1_lines -ne $file2_lines ]
    then
        return 1
    else
        unique_lines=`cat $1 $2 | sort -u | grep -c '.*'`
        if [ $unique_lines -ne $file1_lines ]
        then
            return 1
        else
            return 0
        fi
    fi
}

#-----------------------------------------------------------------------
# If no mpaa.lams file exists, create one.  Otherwise create a temporary
# mpaa.lams file, compare it to the existing file and replace the
# existing file with the temporary one if the two files differ. Also,
# create an empty mpaa.excluded if one doesn't exist
#-----------------------------------------------------------------------
update_lams_files()
{
    local lams_file="/etc/emc/mpaa.lams"
    local lams_excluded_file="/etc/emc/mpaa.excluded"
    local lams_new

    if [ -f "$lams_file" ]; then
        lam_ref=$lams_file
        lams_new=${lams_file}.tmp
    else
        lam_ref=/dev/null
        lams_new=$lams_file
    fi

    echo  "global:version:$PP_VERSION" > $lams_new
    for array in symm clariion hpxp hitachi ess invista vplex vnx
    do
        if tps_managed $array || prev_unmanaged $lam_ref $array
        then
            echo "unmanaged:$array" >> $lams_new
        else
            echo "managed:$array" >> $lams_new
        fi
    done

    if prev_managed $lam_ref hphsx
    then
        echo "managed:hphsx" >> $lams_new
    else
        echo "unmanaged:hphsx" >> $lams_new
    fi

    if [ "$lams_new" = "${lams_file}.tmp" ]; then
        if file_compare $lams_file $lams_new ; then
            rm -f $lams_new
        else
            mv -f $lams_new $lams_file
        fi
    else
        add_to_undolist rm -f $lams_file
    fi

    if [ ! -f "$lams_excluded_file" ]; then
        echo  "global:version:$PP_VERSION" > $lams_excluded_file
        add_to_undolist rm -f $lams_excluded_file
    fi
}

#-----------------------------------------------------------------------
# Add lines to /etc/modprobe.conf.pp to coordinate filter driver, hba
# driver and emcp loading
#-----------------------------------------------------------------------
modprobe_add_pp_lines()
{
    local begin_tag='#begin-hba-'
    local end_tag='#end-hba-'
    local install_hba

    if test "$1"; then
       modprobe_hba=' /sbin/modprobe pp_hba;'
       install_hba=
       for hba in $*
       do
         install_hba="$install_hba /sbin/modprobe $hba;"
       done
    fi

    if grep "^${begin_tag}$1" $modprobe_file > /dev/null; then
        return  # Lines for this hba are already in place
    else
        # Lines indented with tab!!
        cat <<-EOF  >> $modprobe_file
	${begin_tag}${hba}
	install emcp /sbin/modprobe pp_hba; /sbin/modprobe emcp --ignore-install
	install pp_hba ${install_hba}
	${end_tag}${hba}
	EOF
    fi
}

#-----------------------------------------------------------------------
# Create dependencies between HBA drivers and power path drivers.
#-----------------------------------------------------------------------
create_hba_dependencies()
{
    local added_dependency=FALSE
    local searchDir=/lib/modules/`uname -r`
    local qlaHbaName
    local emulexHbaName

    qlaHbaName=`ls -1R /proc/scsi | \
                grep /qla2xxx: | \
                sed -e 's:/proc/scsi/::' -e 's/:$//'`

    emulexHbaName=`ls -1R /proc/scsi | \
                    grep '/lpfc.*:' | \
                    sed -e 's:/proc/scsi/::' -e 's/:$//'`
    if [ "$qlaHbaName" ]; then
        qla_hbas=`lsmod | sed -e 's/ .*//' | grep qla | grep  -v qla2xxx`
        modprobe_add_pp_lines $qla_hbas
        added_dependency=TRUE
    fi

    # We no longer support mixed vendor types, so we will not add the
    # emulex driver if the qla driver exists.

    if [ "$emulexHbaName" -a "$added_dependency" = FALSE ]; then
            emulexHbaName=lpfcdd
            modloc=`ls -1R $searchDir | grep -w "${emulexHbaName}\.ko"`
            if [ "$modloc" ]; then
                modprobe_add_pp_lines $emulexHbaName
            fi
    fi
}

#-----------------------------------------------------------------------
# Add PowerPath parameters to modprobe.conf.pp file
#-----------------------------------------------------------------------
update_driver_parameters()
{
    local lams_file="/etc/emc/mpaa.lams"
    local lams_excluded_file="/etc/emc/mpaa.excluded"

    if [ "$RHEL6_HOST" != "yes" -a "$OL6_HOST" != "yes" -a \
         "$CXS6_HOST" != "yes" ]; then
 
        ## Attach the PP file to modprobe.conf

        grep '^##*BEGINPP' /etc/modprobe.conf >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            save_for_rollback /etc/modprobe.conf
            cat <<-EOF >> /etc/modprobe.conf  ## Lines indented with tabs!!!
		###BEGINPP
		include /etc/modprobe.conf.pp
		###ENDPP
		EOF
        fi
    fi

    copy_file $PPBASE/modprobe.conf.pp $modprobe_file

    ## Update the managedclass parameter line

    mng_class=`awk -F: '(NR == 2) && /^managed/ {printf "%s", $2}
                        (NR > 2) && /^managed/ {printf ",%s", $2}' $lams_file`
    if [ "$mng_class" ] ; then
        if grep "options emcp managedclass" $modprobe_file > /dev/null 2>&1
        then
            sed -i "/managedclass/c\
                    options emcp managedclass=$mng_class" $modprobe_file
        else
            echo "options emcp managedclass=$mng_class" >> $modprobe_file
        fi
    fi

    ## Update the excludedvolumes parameter line.  Put 

    if [ `grep -c '.*' $lams_excluded_file` -gt 1 ] ; then
        excluded=`awk -F: '(NR == 2) {printf "%s", $2}
                           (NR > 2) {printf ",%s", $2}' $lams_excluded_file`
        if [ "$excluded" ] ; then
            if grep "options emcp excludedvolumes" \
                     $modprobe_file > /dev/null 2>&1 ; then
                sed -i "/excludedvolumes/c\
                    options emcp excludedvolumes=$excluded" $modprobe_file
            else
                echo "options emcp excludedvolumes=$excluded" >> \
                    $modprobe_file
            fi
        fi

    fi

    ## Link hba drivers and powerpath drivers

    create_hba_dependencies
}

#-----------------------------------------------------------------------
# update_boot_logic - Tie PowerPath start into system startup logic.
#-----------------------------------------------------------------------
update_boot_logic()
{
    case "$VENDOR" in
        suse)
          MDFILE=/etc/init.d/boot.md
          grep boot.powerpath $MDFILE >> /dev/null 2>>/dev/null 
          if [ $? -eq 1 ]; then
              save_for_rollback $MDFILE
              string=`grep "# Required-Start:" $MDFILE`
              sed --in-place -e "s/$string/$string boot.powerpath/" $MDFILE
              if [ -x /sbin/insserv ]; then
                  /sbin/insserv
              fi
          fi
        ;;
        oracle|citrix|redhat|asianux)
          ETCFILE=/etc/rc.d/rc.sysinit
          grep BEGINPP $ETCFILE  >> /dev/null 2>>/dev/null
          if [ $? -eq 1 ]; then
              save_for_rollback $ETCFILE
              sed --in-place -e '/remount,rw \//a \
                ###BEGINPP\
                # Configure and initialize PowerPath.\
                if [ -f /etc/init.d/PowerPath ]; then\
                   /etc/init.d/PowerPath start\
                fi\
                ###ENDPP' $ETCFILE
          fi
        ;;
    esac
}

#-----------------------------------------------------------------------
# Delete old modules in all /lib/modules subdirectories, then install
# the new modules.
#-----------------------------------------------------------------------
install_driver_modules()
{
for os in /lib/modules/*
do
  case $os in
      /lib/modules/`uname -r`)
          for modpath in $os/powerpath/*
          do
            remove_file $modpath
          done
          ;;
      *)
          remove_dirtree $os/powerpath
          ;;
  esac
  for modpath in $os/extra/emcp*
  do
    remove_file $modpath
  done
done

## Install new modules.

MODULE_BASE=/lib/modules/`uname -r`

make_dir $MODULE_BASE/powerpath

for mod in `ls $PPBASE/bin/driver/$TAG`
do
  copy_mod $PPBASE/bin/driver/$TAG/$mod $MODULE_BASE/powerpath/$mod
done

depmod
}

## Function to satisfy functions in CUSTOMPRE

cleanup_error_exit()
{
   error_exit
}

pre_error()
{
    report_error $1
}

##-------------------------------- Main ------------------------------##

###
### DO NOT REMOVE THE FOLLOWING LINE
# SuSE x86_64 specific:
#

EXPECTED_VENDOR=suse
VENDOR_NAME=Suse
VENDOR_OS_NAME=SLES11SP2
EXPECTED_ISA=x86_64
EXPECTED_OS_REV=11sp2
MIN_UPGRADE_REV=5.1.2

check_vendor_rev()
{
if [ "`cat /etc/SuSE-release | awk '$1 == "PATCHLEVEL" {print $3}'`" ==  "2" ]
then
   sles_version=$EXPECTED_OS_REV
else
   sles_version=""
fi
test "$1" = "$sles_version"
}

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

    case "$1" in
        *-default) platform=sles${EXPECTED_OS_REV}default_x8664 ;;
        *-xen) platform=sles${EXPECTED_OS_REV}xen_x8664 ;;
        *-trace) platform=sles${EXPECTED_OS_REV}trace_x8664 ;;
        *)
          if [ "$1" = `uname -r` ]
          then
              pre_error "This PowerPath package only supports the SuSE SLES x86_64 smp kernel"
              cleanup_error_exit
          fi
          ;;
    esac

    test "$platform" && echo $platform
}
###

init_I18N

rollback_reset

validate_install_target

if [ ${INCLUDE_PPME} = 1 ]; then
  make_dir /etc/emc/ppme
fi

test "$NEW_PP_VERSION" && restore_configuration_files

update_lams_files

update_driver_parameters

install_driver_modules

## Load new modules.  Emcp first, emcpdm, emcpxcrypt, emxpvlumd and emcpioc
## last with everything else in between.

load_all_modules `ls $PPBASE/bin/driver/$TAG | \
              awk '/^emcp.ko$/    {order[$1]=1; next}
                   /^emcpdm.ko$/  {order[$1]=3; next}
                   /^emcpxcrypt.ko$/  {order[$1]=4; next}
                   /^emcpvlumd.ko$/  {order[$1]=5; next}
                   /^emcpioc.ko$/ {order[$1]=6; next}
                   /^emcp/        {order[$1]=2; next}
                   END { for (mod in order) print order[mod],mod;}' |\
              sort -n | \
              sed 's/^.* //'`

## If error loading modules, roll back everything done to this point and
## return an error status.

if [ $? -ne 0 ]
then
   report_error "Error loading PowerPath kernel modules"
   rollback
   rollback_reset
   depmod
   error_exit
fi

## If kernel has changed make sure PowerPath will still start at boot time

if [ "$OS_VERSION" != `uname -r` ]; then
    update_boot_logic    
fi

if [ $? -ne 0 ]
then
   report_error "Error installing PowerPath"
   rollback
   rollback_reset
   error_exit
fi

## Update state info in /etc/opt/emcpower

rm -f $PP_I_DIR/.os_version
uname -r > $PP_I_DIR/.os_version
rm -f $PP_I_DIR/.prev_pp_version
if [ -f $PP_I_DIR/.new_pp_version ]
then
    test -f $PP_I_DIR/.pp_version && \
        mv -f $PP_I_DIR/.pp_version $PP_I_DIR/.prev_pp_version
    mv $PP_I_DIR/.new_pp_version $PP_I_DIR/.pp_version
fi
