#! /bin/bash
###########################################################################
#  Copyright (c) 2003, Hewlett Packard Technologies Group, L. P.           #
############################################################################
#   PROGRAM: install.sh                                                    #
#   PURPOSE: Shell script for initiating the HP Linux Deployment Utility.  #
############################################################################
# $Id: install.sh,v 1.8.2.91 2004/05/17 19:13:32 GarnerMi Exp $
############################################################################

#DEBUG DEBUG DEBUG
# set -x

#################
##    LOCALE   ##
#################

#LANG=ENG

#################
##   GLOBALS   ##
#################
# Change the pass number on this variable for each pass.
TARBALL=hppldu-1.0.3-6.tar.gz
RLS=7.10

# Variables
LCKDIR=/var/lock/hppldu
LCKFILE=${LCKDIR}/hppldu.lock
TMPDIR="/tmp/hppldu"
HPDir="/var/hp"
AUTO=""
SPACE_REQD=70000
pid=99999
RC=0

# Required GDK Library.
GDK_LIB="/usr/lib/libgdk_pixbuf.so.2"
GDK_RPM="gdk-pixbuf-0.18.0-8.1.i386.rpm"
#GDK_RPM_SRC="gdk-pixbuf-0.18.0-8.1.src.rpm"
# Required GTK Library.
GTK_LIB="libgtk-1.2.so.0"
# Required RPMs
GLUT="glut-3.7-12.i386.rpm"
#GLUT_SRC="glut-3.7-12.src.rpm"
COMPAT="compat-libstdc++-7.3-2.96.122.i386.rpm"
#COMPAT_SRC="compat-gcc-7.3-2.96.122.src.rpm"
# Process table command to use.
PSE="ps -e"
# Flag for indicating the user has interrupted our execution.
RFLAG=0
# Color definitions.
GREEN="[1;32m"
BLUE="[1;34m"
RED="[1;31m"
HILITE="[1;39m"
NORMAL="[0;39m"
# Default copy and remove commands to use.
CPCMD="/bin/cp -f"
MVCMD="/bin/mv -f"
RMCMD="/bin/rm -f"
MKDIR="/bin/mkdir -p"
# Some temporary scratch files to use.
TEMP1=/tmp/templsp1.$$
TEMP2=/tmp/templsp2.$$
# Option Preset from commandline.
CMDLINE=false
ItIsRHEL3=false
# Boolean flags for setting states.
BLDRPMDIR=false
STOPPED=false
NOHPASM=false
INTR=false
RO=false
HelpOnly=false
DELAY=false

# Filenames for snmpd.conf files per distribution
RHConfFile="/etc/snmp/snmpd.conf"
SLES7ConfFile="/usr/share/snmp/snmpd.conf"
UL10ConfFile="/usr/share/snmp/snmpd.conf"
tmpConfFile="/var/hp/snmpd.conf.orig"
rpmMacroFile=".rpmmacros"

# Base kernel versions for each supported Linux Distro.
RHAS21="2.4.9-e.24"
RHEL21="2.4.9-e.24"
RHEL3="2.4.21-4"
RH73="2.4.18-3"
RH80="2.4.18-14"
RH90="2.4.20-2.21"
SLES7SMP="2.4.7-19"
SLES7="2.4.7-20"
SLES9="2.6.5-7.5"
SLES964="2.6.5-7.5"
UL10SMP="2.4.19-113"
UL10="2.4.19-120"

# Distro Packages required
RHRPM="rpm"
SURPM="rpm"

#################
##  FUNCTIONS  ##
#################

#Determine which OS this is, and setup the required directories accordingly.
function SetupForOS()
{
    RKRNL=`uname -r`
    if [ -f /etc/redhat-release ]
    then
        RemoteAccess="NFS, or SAMBA"
        GTKLanded "RH"
        RELFILE="/etc/redhat-release"
        CheckKerneldoth
        if [ ! -d /usr/src/redhat ]
        then
            BldDirs "/usr/src/redhat"
            BLDRPMDIR=true
        fi
        export RPMDIR=/usr/src/redhat
            KERNELSRC=`uname -r | sed -e 's/enterprise//' -e 's/debug//' -e 's/[sS][mM][pP]//' -e 's/workstation//' -e 's/bigmem//' -e 's/summit//'`
        export KERNELSRC=/usr/src/linux-`echo $KERNELSRC | tr -d '[A-Da-d][f-mF-Mo-sO-Su-wU-WyYzZ]'`
        Version=`grep "[89]\.[0-9]" </etc/redhat-release`
        if [ ${#Version} -gt 0 ]
        then
            PSE="ps -em"
        fi
        GetDistrVer
        export SNMPDCFGFILE=${RHConfFile}
        if [ -f ${RHConfFile} ]
        then
            ${CPCMD} ${RHConfFile} ${tmpConfFile} >/dev/null 2>&1
        fi
	CheckRPMPkgs "$RHRPM"
    fi
    if [ -f /etc/SuSE-release ]
    then
        RemoteAccess="NFS"
        OS="SU"
        RELFILE="/etc/S?SE-release"
        if [ `grep -ic "suse linux server 9" ${RELFILE}`  -gt 0 ]
        then
            if [ "`uname -m`" = "x86_64" ]
            then
                GTKLanded "SU64"
            else
                GTKLanded "SU9"
            fi
            RKRNL=`uname -r`
            export KERNELSRC=/usr/src/linux-`uname -r | sed -e 's/-[a-zA-Z]*$//'`
        else
            GTKLanded "SU"
            RKRNL=`rpm -qf /boot/vmlinuz`
            export KERNELSRC=/usr/src/linux-`uname -r | sed -e 's/-[-0-9A-Za-z]*$//' -e 's/$/\.SuSE/'`
        fi
        if [ ! -d /usr/src/packages ]
        then
            BldDirs "/usr/src/packages"
            BLDRPMDIR=true
        fi
        export RPMDIR=/usr/src/packages
        GetDistrVer
        export SNMPDCFGFILE=${SLES7ConfFile}
        if [ -f ${SLES7ConfFile} ]
        then
            ${CPCMD} ${SLES7ConfFile} ${tmpConfFile}
        fi
	    CheckRPMPkgs "$SURPM"
    fi
    if [ -f /etc/UnitedLinux-release ]
    then
        RemoteAccess="NFS"
        GTKLanded "UL"
        RELFILE="/etc/UnitedLinux-release"
        if [ ! -d /usr/src/packages ]
        then
            BldDirs "/usr/src/packages"
            BLDRPMDIR=true
        fi
        export RPMDIR=/usr/src/packages
        tKrnl=`uname -r`
        sp3bld=$tKrnl
        tKrnl=${tKrnl#*\.} # Strip the major
        tKrnl=${tKrnl#*\.} # strip the minor
        tKrnl=${tKrnl%%-*} # strip the pass & trailing info
        if [ $tKrnl -ge 21 ]
        then
            export KERNELSRC=/usr/src/linux-`uname -r | sed -e 's/[-A-Za-z]*$//'`
        else
            RKRNL=`rpm -qf /boot/vmlinuz`
            export KERNELSRC=/usr/src/linux-`uname -r | sed -e 's/-[-0-9A-Za-z]*$//' -e 's/$/\.SuSE/'`
        fi
        # Are we running one of the SP3 kernels?
        sp3bld=${sp3bld#*-}
        sp3bld=`echo $sp3bld | sed 's/[-A-Za-z.]*$//'`
        if [ -n $sp3bld -a $sp3bld -ge 85  ]
        then
            export SP3=YES
            export KRNLCFG="/boot/config-`uname -r`"
        else
            export SP3=NO
            export KRNLCFG="/boot/vmlinuz*.config"
        fi
        GetDistrVer
        export SNMPDCFGFILE=${UL10ConfFile}
        if [ -f ${UL10ConfFile} ]
        then
            ${CPCMD} ${UL10ConfFile} ${tmpConfFile}
        fi
	CheckRPMPkgs "$SURPM"
    fi

#    # Lets see if we have kernel source available.
    avail="`ls $KERNELSRC 2>/dev/null`"
    if [  \( ! -d $KERNELSRC -o -z "$avail" \) -a "$HelpOnly" = "false" -a "$SILENT" = "false" ]
    then
        ans=""
        if [ "$SILENT" = "false" ]
        then
            putmsg "\nThe HP ProLiant Linux Deployment Utility requires source code\nfor the ${BLUE}${RKRNL}${NORMAL} kernel be available for building and installing\ncertain drivers included in this bundle.\nThe directory, ${BLUE}$KERNELSRC${NORMAL}, is either missing, or is empty.\n\nKernel source code may also be made available via ${RemoteAccess} from a\nremote system.\n\nDo you wish to continue? [Y] \c" 30
            CheckAns "y"
        else
            ans="y"
        fi
        if [ "$ans" != "y" ]
        then
            HelpOnly=true  # Using this flag to prevent restarting daemons.
            cleanup "\nPlease install the RPM package for the ${BLUE}`echo $RKRNL|sed 's/[-a-zA-Z]*$//'`${NORMAL} kernel source code,\nand restart the HP ProLiant Linux Deployment Utility.\n"
            exit 23
        fi
    fi

    # Now lets protect the rpmmacro file if present.
    if [ -f ${HOME}/${rpmMacroFile} ]
    then
        ${CPCMD} ${HOME}/${rpmMacroFile} ${HPDir}/${rpmMacroFile}
    fi
    return
}

# This function is to ensure that we have a clean /boot/kernel.h
# for compiling certain of the component drivers.
function CheckKerneldoth()
{
    file=/sbin/mkkerneldoth # initscript for creating the /boot/kernel.h file during bootup.
    tfile=/tmp/mkkernel.h   # temporary scratch file.

    # Scan the initscript to determine which types of kernels this system will support.
    # then ID the types that are initialized.  The purpose of this function is to ensure
    # that all types supported are initialized to a 0 value.  Then the script will set
    # the value of the running kernel type to 1.

    if [ -s $file ]
    then
        k_types=`cat $file|egrep "^KERNEL_TYPE"|awk -F\) '{print $1}'|awk -F\( '{print $2}'|sed 's/\\\//g'|tr "|" " "`
        k_types="$k_types up"
        K_TYPES=`egrep "^  [A-Z]*='0'" $file`
        k_cnt=`echo $k_types|wc -w`
    else
        return
    fi
    touch $tfile
    str=""
    for j in $K_TYPES
    do
        pos=`expr index $j '='`
        (( pos-- ))
        str="$str `echo ${j:0:$pos}|tr [:upper:] [:lower:]`"
    done
    lineno=0
    for i in $k_types
    do
        matched=0
        if [ ${#i} -ne 0 ]
        then
            matched=`echo $str|grep -c $i`
        fi
        if [ $matched -eq 0 ]
        then
            newstr=`echo $i|tr [:lower:] [:upper:]`
	        echo "# The following line was added by the HP ProLiant Linux Deployment Utility" >> $tfile
	        echo "# to fix a bug in the original script that was preventing certain NIC drivers" >> $tfile
	        echo "# from compiling." >>$tfile
	        echo >>$tfile
	        echo "  $newstr='0'" >> $tfile
	        echo >>$tfile
        else
            (( match_cnt++ ))
        fi
    done
    if [ $k_cnt -ne $match_cnt ]
    then
        cat $file >> $tfile
        chmod 755 $tfile
        $MVCMD $tfile $file
        $MVCMD /boot/kernel.h /boot/kernel.h.orig
        $file
    fi
    return
}


function CheckRPMPkgs()
{
    rpm_cnt=0
    for i in $1
    do
    	rpm -q $i >/dev/null 2>&1
    	if [ $? -ne 0 ]
    	then
    		let "rpm_cnt += 1"
    	fi
    done
    case $rpm_cnt in
        1)  putmsg "\nA required package, ${BLUE}rpm-devel${NORMAL}, is not installed on this system.\nYou will not be able to install some of the components in this bundle.\n\nPlease insure the following required packages are installed:\n$1\n\nand re-run the HP ProLiant Linux Deployment Utility.\n" 10
	    exit 3
            ;;
        2)  putmsg "\nRequired packages, ${BLUE}rpm-devel and rpm-build${NORMAL}, are not installed on this system.\nYou will not be able to install some of the components in this bundle.\n\nPlease insure the following required packages are installed:\n$1\n\nand re-run the HP ProLiant Linux Deployment Utility.\n" 10
	    exit 3
            ;;
        3)  putmsg "\nRequired packages, ${BLUE}rpm, rpm-devel and rpm-build${NORMAL}, are not installed on this system.\nYou will not be able to install some of the components in this bundle.\n\nPlease insure the following required packages are installed:\n$1\n\nand re-run the HP ProLiant Linux Deployment Utility.\n" 10
	    exit 3
	    ;;
	0)  ;;
    esac
    return
}
	

# Function for formatting user responses.
function CheckAns()
{
    if [ ${#ans} -eq 0 ]
    then
        ans="$1"
    fi
    ans=`echo ${ans:0:1}|tr [:upper:] [:lower:]`
    return
}

# Function for establishing the RPM Build dirtree if not present.
function BldDirs()
{
    RootDir=$1
    rc=999
    while [ $rc -ne 0 ]
    do
        rc=0
        $MKDIR ${RootDir}/BUILD >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/athlon >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/i386 >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/i486 >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/i586 >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/i686 >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/RPMS/noarch >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/SOURCES >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/SPECS >/dev/null 2>&1
        rc=`expr $rc + $?`
        $MKDIR ${RootDir}/SRPMS >/dev/null 2>&1
        rc=`expr $rc + $?`
        if [ $rc -ne 0 ]
        then
            putmsg "\nA directory tree at ${RPMDIR} does not appear to be present\non this system.\nIf this dirtree is not present, some of the components will not install properly.\nDo you wish to continue? (Default = No)  \c" 30
            CheckAns "N"
            if [ "$ans" = "y" ]
            then
                return
            else
                cleanup "\nThe user aborted installation of the HP ProLiant Linux Deployment Utility.\n\n"
                exit 23
            fi
        fi
        return
    done
}


# Function for locating required GTK libraries.
function GTKLanded()
{
    case "$1" in
       "SU9")  GTK_DIR=/opt/gnome/lib/
               ;;
      "SU64")  GTK_DIR=/opt/gnome/lib64/
               ;;
           *)  GTK_DIR=/usr/lib/
    esac
    GTK_LIB_PATH="${GTK_DIR}${GTK_LIB}"
    if [ ! -e ${GTK_LIB_PATH} ]
    then
        putmsg "\nA necessary graphics library, (${BLUE}${GTK_LIB_PATH}${NORMAL}) required by the\nHP ProLiant Linux Deployment Utility GUI is not installed on this server.\n\nAccordingly, the Graphical User Interface cannot be used.\n\nThe process will continue in Text mode.\c" 0
        sleep 3
        GUI="false"
    fi
    return
}

# Function for verifying the presence of required RPM packages.
function CheckInstalledRPMs()
{
    flag=0
    cnt=`rpm -q ${COMPAT%%-[0-9]*} | grep -c "not installed"`
    if [ $cnt -gt 0 ]
    then
        flag=$(( flag + 1 ))
    fi
    cnt=`rpm -q ${GLUT%%-[0-9]*} | grep -c "not installed"`
    if [ $cnt -gt 0 ]
    then
        flag=$(( flag + 2 ))
    fi
    case $flag in
        1) file=$COMPAT
           msg="\nAn RPM package, ${BLUE}${file}${NORMAL}, required for the\nsuccessful installation of the:\n\n\tHP Storage Agents for Linux.\n\tHP Array Configuration Utility for Linux.\n\tHP Insight Diagnostics Online Edition for Linux.\n\tHP Version Control Agent for Linux.\n\tHP Tested and Approved Linux 802.1q VLAN Driver.\n\nis not present on this system.\nThe ${BLUE}${file}${NORMAL} package is that from the Red Hat\ndistibution CD and is included with this bundle.\nIf you proceed without installing the RPM, the above listed components will not install.\nDo you wish to install the RPM now? [Y] \c"
          ;;
        2) file=$GLUT
           msg="\nAn RPM package, ${BLUE}${file}${NORMAL}, required for the successful\ninstallation of the:\n\n\tHP Insight Diagnostics Online Edition for Linux\n\nis not present on this system.\n\nThe ${BLUE}${file}${NORMAL} package is that from the Red Hat\ndistibution CD and is included in this bundle.\nIf you proceed without installing the RPM, the above listed component will not install.\nDo you wish to install the RPM now? [Y] \c"
           ;;
        3) file="$COMPAT & $GLUT"
           msg="\nThe RPM packages, ${BLUE}${file}${NORMAL},\nrequired for the successful installation of:\n\tHP Storage Agents for Linux.\n\tHP Array Configuration Utility for Linux.\n\tHP Insight Diagnostics Online Edition for Linux.\n\tHP Version Control Agent for Linux.\n\tHP Tested and Approved Linux 802.1q VLAN Driver.\nare not present on this system.\n\nThe ${BLUE}${file}${NORMAL} packages\nare those from the Red Hat distibution CD and are included in this bundle.\nIf you proceed without installing the RPMs, the above listed components\nwill not install.\n\nDo you wish to install the RPMs now? [Y] \c"
           ;;
        *) return
           ;;
    esac
    putmsg "$msg" 30
    CheckAns "Y"
    if [ "$ans" != "y" ]
    then
        return
    fi
    declare -a failed
    fail=0
    ptr=1
    if [ "$RO" = "true" ]
    then
        cd $TMPDIR
    else
        cd $ORIGDIR
    fi
    for i in `echo $file|tr -d '&'`
    do
        if [ ! -f $i ]
        then
            extractRPM $i
        fi
        [ "$SILENT" = "false" ] && echo -e "Installing $i.....\c"
        rpm -ihv $i >/dev/null 2>&1
        if [ $? -ne 0 ]
        then
            fail=1
            failed[$ptr]=$i
            [ "$SILENT" = "false" ] && echo -e "${RED}Failed!${NORMAL}"
            (( ptr++ ))
        else
            sleep 1
            [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}"
        fi
    done
    sync;sync
    if [ -f /var/hp/hpverdb.xml ]
    then
        [ "$SILENT" = "false" ] && echo -e  "Updating the RPM database....\c"
        rpm --rebuilddb >/dev/null 2>&1
        [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}"
    fi
    if [ $fail -ne 0 ]
    then
        (( ptr-- ))
        str="\n\t"
        while [ $ptr -gt 0 ]
        do
            str="${str}\n\t${failed[$ptr]}"
            (( ptr-- ))
        done
        putmsg "\n\n${RED}ERROR: The $str\n\npackage/s failed to install.${NORMAL}\nPlease determine the cause and re-install.\n\nPress <ENTER> to continue.\c" 99
    fi
    return
}

# Function for extracting selected RPMs from tarball.
function extractRPM()
{
    if [ ${#1} -eq 0 ]
    then
        return
    else
        tar -xzf $TARBALL "${1}"
    fi
    return
}



# Function for verifying the presence of required gdk library on RHEL3.
function CheckGDKLib()
{
    if [ "$TERM" = "linux" -a ${#AUTO} -eq 0 ]
    then
        GUI=false
    fi
    if [ "$GUI" = "false" ]
    then
       return
    else
       GUI=true
    fi
    PROMPT=false
    LIB=$GDK_LIB
    RPM=$GDK_RPM
    if [ ! -s "$LIB" ]
    then
        ans=""
        putmsg "\nA necessary graphics library, (${BLUE}${LIB}${NORMAL},\nprovided by the ${BLUE}${RPM}${NORMAL}) required by the\nHP ProLiant Linux Deployment Utility GUI is not installed on this server.\nDo you want the LDU to install the RPM providing this library\nand continue the installation [default=Y]? \c" 30
        CheckAns "Y"
        if [ "$ans" = "y" ]
        then
            extractRPM $RPM
            if [ -s "$RPM" ]
            then
                /bin/rpm -iv $RPM >/dev/null 2>&1
                [ $? -eq 0 ] && return
                putmsg "\nERROR: The installation of ${BLUE}$RPM${NORMAL} was not successful.\nDo you wish to continue the Linux ProLiant Support Pack installation\nwithout the GUI [default=Y]? \c" 30
                CheckAns "Y"
                if [ "$ans" = "y" ]
                then
                    GUI=false
                else
                    cleanup "\nThe user aborted installation of the HP ProLiant Linux Deployment Utility.\n\n"
                    exit 23
                fi
            else
                putmsg "\nThe RPM, ${BLUE}$GDK_RPM${NORMAL}, is missing or corrupt\nand cannot be installed at this time." 99
                PROMPT=true
            fi
        else
            PROMPT=true
        fi
    fi
    if [ "$PROMPT" = "true" ]
    then
        putmsg "\nDo you wish to continue the Linux ProLiant Support Pack\ninstallation without the GUI [default=Y]? \c" 30
        CheckAns "Y"
        if [ "$ans" = "y" ]
        then
            GUI=false
        else
            cleanup "\nThe user aborted installation of the HP ProLiant Linux Deployment Utility.\n\n"
            exit 23
        fi
    fi
    return
}


# Function for determining if ELM has passwords configured.
function IsELMCfg()
{
    export CMAFDTNECHO=yes
    export LSPELMCONFIGURED=NO
    if [ -x /opt/compaq/foundation/etc/hpwebsetup ]
    then
        /opt/compaq/foundation/etc/hpwebsetup -q: >/dev/null 2>&1
        if [ $? = 4 ]; then
            export LSPELMCONFIGURED=YES
        fi
    fi
    return
}

# Function for determining which Bundle File we need to use.
function GetBundle()
{
    if [ ! $Identified ]
    then
        cleanup "\n\nThe Linux O/S on this system cannot be identified\nby the HP ProLiant Linux Deployment Utility.\nPlease check $RELFILE for correctness.\nCannot continue.  Exiting.\n"
        exit 999
    fi
    for i in `ls $ORIGDIR/BP*`
    do
        if [ ${#i} -ne 0 -a ${#os} -ne 0 -a ${#version} -ne 0 ]
        then
            grep -i "operating_system_xlate" $i >/tmp/bfile
            while read line
            do
                if [ `echo $line|grep -ic "$os $version"` -gt 0 ]
                then
                    BUNDLE=$i
                    break
                fi
            done < /tmp/bfile
            ${RMCMD} /tmp/bfile >/dev/null 2>&1
        fi
    done
    if [ -z "$BUNDLE" ]
    then
        HelpOnly=true
        cleanup "\nThe ${RLS} release of the HP Linux Deployment Utility\ndoes not include support for ${os} ${version}.\n\nPlease visit the www.hp.com/linux website for available support.\n"
        exit 3
    fi
    if [ "$SILENT" = "false" ]
    then
        putmsg "\n\nBecause of Read-Only media, the HP ProLiant Linux Deployment Utility\nis copying the files to a temporary work location.\n\nThis may take several seconds..." 55
    fi
    grep -n "<package install=\"yes\">" $BUNDLE | awk -F\> '{print $2}'| awk -F\< '{print $1}' > $TEMP1
    while read LOOP1 LOOP2
    do 
    #    echo $LOOP1
        ${CPCMD} $ORIGDIR/$LOOP1 ${TMPDIR} >/dev/null  2>&1
    done < $TEMP1
    sed 's/.rpm/.xml/g' $TEMP1 > $TEMP2
    while read LOOP1 LOOP2
    do
    #    echo $LOOP1
        ${CPCMD} $ORIGDIR/$LOOP1 ${TMPDIR} >/dev/null  2>&1
    done < $TEMP2
    ${RMCMD} /tmp/templsp*.$$
    ${CPCMD} $ORIGDIR/install???.sh ${TMPDIR} >/dev/null  2>&1
    ${CPCMD} $ORIGDIR/hppldu-*.tar.gz ${TMPDIR} >/dev/null  2>&1
    ${CPCMD} $ORIGDIR/*.txt ${TMPDIR} >/dev/null 2>&1
    [ $pid -ne 99999 ] && kill $pid >/dev/null 2>&1
    pid=99999
    return
}

function GetOpts()
{
    if [ "$TERM" = "linux" ]
    then
        if [ ${#AUTO} -gt 0 ]
        then
            GUI=true
        else
            GUI=false
        fi
    else
        GUI=true
    fi
    SILENT=false
	for i in $1
	do
        opt=`echo $i|tr [:upper:] [:lower:]`
		if [ "$opt" = "-s" -o "$opt" = "--silent" -o "$opt" = "-silent" -o "$opt" = "-c" ]
		then
			GUI=false
            CMDLINE=true
            SILENT=true
        elif [ "$opt" = "-c" ]
        then
            DELAY=true
		elif [ "$opt" = "--nui" -o "$opt" = "-nui" ]
        then
            CMDLINE=true
        elif [ "$opt" = "-h" -o "$opt" = "-help" -o "$opt" = "--help" -o "$opt" = "-?" -o "$opt" = "-v" -o "$opt" = "--view" -o "$opt" = "-view" ]
        then
            HelpOnly=true
        fi
	done
    return
}


# Function for IDing the OS, Version and Base Kernel version.
function GetDistrVer()
{
    BASEKRNL=""
    Identified=false
    krnl=`uname -r`
    ktype=`echo $krnl|grep -i smp`
    for File in /etc/redhat-release /etc/SuSE-release /etc/UnitedLinux-release
    do
        if [ -f ${File} ]
        then
            if [ `grep -c "Red Hat" $File` -gt 0 ]
            then
                if [ `grep -c "Red Hat Enterprise" $File` -gt 0 ]
                then
                # we found a RedHat Enterprise Linux
                    version=`cat $File | awk '{print $6}'`
                    if [ "$version" = "release" ]
                    then
                        # Must be RHEL21
                        version=`cat $File | awk '{print $7}'`
                        if [ "$version" != "3" ]
		                then
                            BASEKRNL=$RHEL21
                        else
                            BASEKRNL=$RHEL3
                            IsItRHEL3=true
                            export KERNELSRC=/usr/src/linux-`uname -r|tr -d "[a-z]"`
                        fi
                    fi
                    os="Red Hat Enterprise Linux"
                    [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
                elif [ `grep -c Advanced $File` -gt 0 -o `grep -c AS $File` -gt 0 ]
                then
                    # we found a RedHat Advanced Server Linux
                    version=`cat $File | awk '{print $7}'`
                    if [ "$version" = "2.1AS" ]
                    then
                        os="Red Hat Enterprise Linux"
                        version=`echo $version|sed 's/AS//'`
                        BASEKRNL=$RHAS21
                    else
                        os="Red Hat Advanced Server"
                        BASEKRNL=$RHAS21
                    fi
                    [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
                elif [ `grep -c "Red Hat Linux" $File` -gt 0 ]
                then
                    # we found a RedHat Linux Professional system.
                    version=`cat $File | awk '{print $5}'`
                    os="Red Hat Linux"
                    case "$version" in
                        "7.3") BASEKRNL=$RH73 ;;
                        "8.0") BASEKRNL=$RH80
                               CheckRPM ;;
                            *) ;;
                    esac
                    [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
                fi
            elif [ `grep -c "UnitedLinux" $File` -gt 0 ]
            then
                version=`cat $File | awk '{if(NR == 1) {print $2}}'`
                os="UnitedLinux"
                if [ -n "$ktype" ]
                then
                    BASEKRNL=$UL10SMP
                else
                    BASEKRNL=$UL10
                fi
                [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
            elif [ `grep -ic "S[Uu]SE SLES-7" $File` -gt 0 ]
            then
                if [ -n "$ktype" ]
                then
                    BASEKRNL=$SLES7SMP
                else
                    BASEKRNL=$SLES7
                fi
                version=`cat $File | awk '{if(NR == 2) {print $3}}'`
                version=${version:0:1}
                os="SUSE LINUX Enterprise Server"
                [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
	        elif [ `grep -ic "sles-9" $File` -gt 0 ]
            then
                if [ "`uname -m`" = "x86_64" ]
                then
                    BASEKRNL=SLES964
                else
                    BASEKRNL=SLES9
                fi
                version=`cat $File | awk '{if(NR == 2) {print substr($3,0,1)}}'`
                os="SUSE LINUX Server"
                [ ${#version} -gt 0 -a ${#os} -gt 0 ] && Identified=true
            fi
        fi
    done
    # Now we have identified the Base Kernel, lets move it to the environment.
    export BASEKRNL
    return
}


#Function for displaying messages to user.
function putmsg()
{
    [ "$SILENT" = "true" ] && return
    [ $2 -eq 99 ] && timer=999 || timer=$2
    # Make sure we have the display program available.
    if [ ! -s $HPDir/displayit.sh ]
    then
cat >$HPDir/displayit.sh <<-END
echo -e \$1
read ans
echo \$ans >/tmp/tmpans
END
    chmod 700 $HPDir/displayit.sh
    fi
    # Display the message either on a popup or console.
    old_resume=${auto_resume}
    unset auto_resume
    answered=0
    if [ ${#AUTO} -gt 0 ]
    then
        xterm -bg white -fg black -T "NOTICE!!!" -hold -e $HPDir/displayit.sh "$1" >/dev/null 2>&1 &
        pid=$!
        [ $2 -eq 55 ] && return
    else
        echo -e "$1"
        [ $2 -eq 55 ] && return
        if [ ${#1} -gt 0 ]
        then
            read -t $timer ans
        fi
        return
    fi
    if [ ${#1} -gt 0 ]
    then
        while [ $timer -gt 0 ]
        do
            if [ -s /tmp/tmpans ]
            then
                answered=1
                read ans </tmp/tmpans
                $RMCMD /tmp/tmpans >/dev/null 2>&1
                break
            fi
            sleep 1
            (( timer++ ))
        done
    fi
    ${RMCMD} /tmp/tmpans >/dev/null 2>&1
    [ $pid -ne 99999 ] && kill $pid >/dev/null 2>&1
    pid=99999
    [ ${#answered} -eq 0 ] && ans="Y"
    set auto_resume=$old_resume
    return
}


# Function for validating the RPM package on RH80 systems.
function CheckRPM()
{
    if [ "$GUI" = "false" -o "$SILENT" = "true" -o "$HelpOnly" = "true" ]
    then
        return
    fi
    RPMQ=`$PSE  | grep rpm`
    if [ ${#RPMQ} -gt 0 ]
    then
        ans=""
        putmsg "\nThe RPM database on this system appears to be open, or locked.\nAccordingly, the HP ProLiant Linux Deployment Utility cannot continue.\nPlease refer to Bugzilla Issue #73097 for instructions on how to resolve\nthis condition.\n\nPlease resolve the issue and re-start the HP ProLiant Linux Deployment Utility.\n\nExiting...\n" 99
         exit 23
   fi
   return
}


# Function for cleaning up the work area.
function cleanup()
{
    # Ensure all buffers are flushed.
    sync;sync
    # Remove the lock.
    if [ -d $LCKDIR -a ${RFLAG} -eq 1 ]
    then
       rm -rf $LCKDIR >/dev/null 2>&1
    fi
    # Restore the user terminal
    tput cnorm
    # Determine if we need to restart the agents.
    if [ -f /var/spool/compaq/cma.install ]
    then
    	$RMCMD /var/spool/compaq/cma.install >/dev/null 2>&1
    fi
    if [ -s /opt/compaq/hpasm/etc/hpasm -o "$STOPPED" = "true" -o "$NOHPASM" = "true" ]
    then
        RESTARTEM=true
    fi
    if [ "$HelpOnly" = "false" ] #-a $RC -ne 16 ]
    then
        if [ "$RESTARTEM" = "true" -a \( "$INTR" = "false" -a -f /tmp/didit.tmp \) ]
        then
           [ "$SILENT" = "false" ] && echo -e "\nRestarting hpasm management daemons...\c"
           /etc/init.d/hpasm restart >/dev/null 2>&1
           [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}\n"
        elif [ "$RESTARTEM" = "true" -a \( "$INTR" = "true"  -o ! -f /tmp/didit.tmp \) ]
        then
           [ "$SILENT" = "false" ] && echo -e "\nRestarting hpasm management daemons...\c"
           /etc/init.d/hpasm restart >/dev/null 2>&1
           [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}\n"
        fi
    fi
    if [ -s /usr/share/diagnostics/hpdiags-bin -a \( "$STOPPED" = "true" -o "$NOHPASM" = "true" \) ]
    then
        RESTARTDIAGS=true
    fi
    if [ "$HelpOnly" = "false" ] #-a $RC -ne 16 ]
    then
      if [ "$IsItRHEL3" = "true" ]
      then
        if [ "$RESTARTDIAGS" = "true" -a \( "$INTR" = "false" -a -f /tmp/didit.tmp \) ]
        then
           [ "$SILENT" = "false" ] && echo -e "\nRestarting HP Insight Diagnostics Online Edition for Linux...\c"
           /etc/init.d/hpdiags start >/dev/null 2>&1
           [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}\n"
        elif [ "$RESTARTDIAGS" = "true" -a \( "$INTR" = "true"  -o ! -f /tmp/didit.tmp \) ]
        then
           [ "$SILENT" = "false" ] && echo -e "\nRestarting HP Insight Diagnostics Online Edition for Linux...\c"
           /etc/init.d/hpdiags restart >/dev/null 2>&1
           [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}\n"
        fi
      fi
    fi
    # See if we need to cleanup any Remote Access mounts/directories.
    if [ ${#KERNELSRC} -ne 0 ]
    then
        MTD=`mount | grep $KERNELSRC 2>/dev/null`
        if [ -n "$MTD" ]
        then
            umount $KERNELSRC 1>/dev/null 2>&1
        fi
        if [ -d $KERNELSRC ]
        then
            /bin/rmdir $KERNELSRC 1>/dev/null 2>&1
        fi
    fi
    # Lets restore the .rpmmacros file if we copied it.
    if [ -f ${HPDir}/${rpmMacroFile} ]
    then
        ${MVCMD} ${HPDir}/${rpmMacroFile} ${HOME}/${rpmMacroFile}
    fi
    # Did we have to build the RPM directory tree?
    if [ "$BLDRPMDIR" = "true" ]
    then
       /bin/rm -rf ${RPMDIR} >/dev/null 2>&1
    fi
    # Did we have to copy the files to a /tmp directory?
    # If so, we need to clean it up, or just cleanup here.
    unset HPLSPINSTALL KERNELSRC RPMDIR BASEKRNL LSPELMCONFIGURED SNMPDCFGFILE
    if [ -d $TMPDIR -a $RFLAG -eq 1 ]
    then
       cd $ORIGDIR 
       /bin/rm -rf ${TMPDIR} >/dev/null 2>&1
    elif [ $RFLAG -eq 1 ]
    then
        ${RMCMD} hppldu >/dev/null 2>&1
        ${RMCMD} hpplduparserss >/dev/null 2>&1
        ${RMCMD} hpplduioss >/dev/null 2>&1
        ${RMCMD} hppldudepchkss >/dev/null 2>&1
        ${RMCMD} hpplduinstallerss >/dev/null 2>&1
        ${RMCMD} hpplduverchkdbss >/dev/null 2>&1
        ${RMCMD} hppldu.conf >/dev/null 2>&1
        ${RMCMD} hppldu.prm >/dev/null 2>&1
        ${RMCMD} ncmcon.cfg >/dev/null 2>&1
        ${RMCMD} libcpqlsp* >/dev/null 2>&1
        ${RMCMD} install\?\?\?.sh >/dev/null 2>&1
        ${RMCMD} ${HPDir}/displayit.sh >/dev/null 2>&1
        ${RMCMD} ${GDK_RPM} >/dev/null 2>&1
#        ${RMCMD} ${GDK_RPM_SRC} >/dev/null 2>&1
        ${RMCMD} ${GLUT} >/dev/null 2>&1
#        ${RMCMD} ${GLUT_SRC} >/dev/null 2>&1
        ${RMCMD} ${COMPAT} >/dev/null 2>&1
#        ${RMCMD} ${COMPAT_SRC} >/dev/null 2>&1
        ${RMCMD} /usr/lib/libcpqlsptransport.* >/dev/null 2>&1
        ${RMCMD} /tmp/didit.tmp >/dev/null 2>&1
    fi
    # Move to the original working directory and get ready to exit.
    cd $ORIGDIR
    # Echo message, if any, to user.
    if [ -n "$1" ]
    then
        putmsg "$1" 0
    fi
    # Clear the traps.
    trap '' 2 3 15
    
    # Then return.
    return
}


# Function for killing all hppldu processes.
function killer()
{
    # Identify all our appl processes.
    PIDs=`${PSE}|grep hppldu|awk '{print $1}'|sort -r`
    # Now kill them one at a time. (use SIGKILL to make sure)
    for k in $PIDs
    do
        kill -9 $k >/dev/null 2>&1
    done
    return
}

# Function for catching a user interrupt, then
# terminate our HPPLDU.
function interrupt()
{
    # Set a flag to indicate interrupt has occurred.
    INTR=true
    # Call killer to terminate all hppldu processes.
    killer
    # Set the remove flag.
    RFLAG=1
    # Call the cleanup crew.
    cleanup "$1"
    # and, get out!
    exit $RC
}

function SetProcTypeAndArchitecture()
{
    ARCHITECTURE=`uname -m`
    export ARCHITECTURE

    VALUE=`cat /proc/cpuinfo | grep -i genuineintel | sed 's/[ ]//g'`
    if [ -n "$VALUE" ]
    then
      PROC_TYPE="INTEL"
    else
      VALUE=`cat /proc/cpuinfo | grep -i authenticamd | sed 's/[ ]//g'`
      if [ "$VALUE" != "" ]
      then
        PROC_TYPE="AMD"
      else
        PROC_TYPE="INTEL"
      fi
    fi
    export PROC_TYPE
    return
}

###################################
##                               ##
##          M A I N              ##
##                               ##
###################################
# Lets make verify that 'superuser' is running this appl.
if [ `id -u` -eq 0 ]
then
    AUTO=${SS_CD_MOUNTPOINT}
    # Set some traps.
    trap 'interrupt "\nTerminated!\n"' 2
    trap 'cleanup ""' 1 3 15
    SetProcTypeAndArchitecture
    
    

    # Remove an empty lock directory
    if [ -d ${LCKDIR} -a ! -s ${LCKFILE} ]
    then
      rmdir $LCKDIR
    fi

    # Now setup a lock, so that we only allow one instance of
    # the HPPLDU to run at a time.
    if [ ! -d ${LCKDIR} ]
    then
        $MKDIR $LCKDIR >/dev/null 2>&1
        echo $$ >$LCKFILE
    else
        ISITCURR=0
        CHKLCK=`cat $LCKFILE 2>/dev/null`
        [ -n "$CHKLCK" ] && ISITCURR=`$PSE | grep $CHKLCK`
        if [ ${#ISITCURR} -gt 0 ]
        then
            RFLAG=0
            cleanup "\nOnly one instance of the HP ProLiant Linux Deployment Utility\nmay run at a time.\n"
            exit 21   # Exit Code = LSP_APPLICATION_ALREADY_RUNNING
        else
            echo $$ >$LCKFILE
        fi
    fi

    # Setup our HP directory if needed.
    if [ ! -d $HPDir ]
    then
        $MKDIR $HPDir
        [ $? -ne 0 ] && cleanup "Unable to create $HPDir..this directory is required for\nstoring certain files used with the HP ProLiant Linux Deployment Utility."
    fi

    # Determine the path to our executables, and move there.
    ORIGDIR=`dirname $0`
    if [ "$ORIGDIR" = "." ]
    then
       ORIGDIR=$PWD
    fi

    # Lets make the command line options local.
    GetOpts "$@"

    # Which Distr. of Linux are we on.
    SetupForOS

    #Set lock file for foundation and server agents
    sync;sync
#    if [ ! -f /var/hp/hpverdb.xml -a "$IsItRHEL3" = "true" ]
#    then
#        [ "$SILENT" = "false" ] && echo -e  "Rebuilding the RPM database....\c"
#        rpm --rebuilddb >/dev/null 2>&1
#	    [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}"
#    fi

    touch ${ORIGDIR}/install???.sh >/dev/null 2>&1
    if [ $? -ne 0 ]
    then
        RO=true  # This is a READ-ONLY directory.
        if [ ${#AUTO} -gt 0 ]
        then
            CDDEV=$MNTDEV
        else
            CDDEV=`df -k $ORIGDIR|awk '{if( NR > 1) print $1}'`
        fi
        export CDDEV
        SPACE_AVAIL=`df /tmp |  awk '{if(NR > 1) print $4}'`
        if [ $SPACE_AVAIL -ge $SPACE_REQD ]
        then
            $MKDIR $TMPDIR >/dev/null 2>&1    # Create a temporary work space.
            if [ $? -ne 0 ]
            then
                cleanup "\n\nUnable to create a temporary working directory in '/tmp'.\nPlease verify, or set '/tmp' for proper permissions, and re-run\nthe HP ProLiant Linux Deployment Utility."
            exit 1
            fi
            GetBundle
            ${CPCMD} ${BUNDLE} ${TMPDIR} >/dev/null 2>&1
            cd ${TMPDIR}
        else
            cleanup "\n\nThere is inadequate disk space available in '/tmp' to execute\nthe HP ProLiant Linux Deployment Utility.\n Exiting...\n"
            exit 1
        fi
    fi

    # See if we are on RH EL3, if so verify libgdk_pixbuf.so.2 and required RPMs are present.
    if [ "$IsItRHEL3" = "true" ]
    then
        CheckGDKLib
        CheckInstalledRPMs
        #  The next two lines were added to fix the RHEL3 rpm database corruption issue.
        export LD_ASSUME_KERNEL=2.4.1  
        export RPM_FORCE_NPTL=1
    fi

    # Well we finally got thru all the preliminaries, so now
    # we can get down to business.
    # Setup the execution environment. 
    tar zxf ${TARBALL} >/dev/null

    # Is HPASM installed, and are the agents running, if so, stop them.
    if [ "$HelpOnly" = "false" ]
    then
        # Is the hpasm running?
        ASM=`ps -e | grep cmapeerd`
        if [ ${#ASM} -ne 0 ]
        then
           [ "$SILENT" = "false" ] && echo -e "\nStopping hpasm management daemons.....\c"
           /etc/init.d/hpasm stop cmafdtn >/dev/null 2>&1
           STOPPED=true
           [ "$SILENT" = "false" ] && echo -e "${GREEN}Done${NORMAL}\n"
        else
           ASM=`/bin/rpm -q hpasm 2>&1|grep "not installed"`
           if [ ${#ASM} -ne 0 ]
           then
               NOHPASM=true
           fi
        fi
    fi

    if [ -f /var/spool/compaq/cma.install ]
    then
    	$RMCMD /var/spool/compaq/cma.install >/dev/null 2>&1
    fi
    if [ ! -d /var/spool/compaq ]
    then
	    $MKDIR /var/spool/compaq >/dev/null 2>&1
    fi
    echo "cmafdtn cmasvr" > /var/spool/compaq/cma.install 

    # Is ELM configured with passwords?
    IsELMCfg
    ln -sf libcpqlsptransport.so.0.0 libcpqlsptransport.so.0 >/dev/null 2>&1
    ln -sf libcpqlsptransport.so.0 libcpqlsptransport.so >/dev/null 2>&1
    ${CPCMD} libcpqlsptransport.so.0.0 /usr/lib/ >/dev/null 2>&1
    /sbin/ldconfig >/dev/null 2>&1
    HPLSPINSTALL=TRUE
    export HPLSPINSTALL

    # Then kick off the Application.
    RFLAG=1
    if [ "$GUI" = "false" -a "$CMDLINE" = "false" ]
    then
        ./hppldu  $@ "--nui"
    else
        ./hppldu "$@" 
    fi
    # Capture the return code from the HPPLDU.
    RC=$?
    #  echo "RC is "$RC

    # Delay for a few seconds if we are running a VCA install.
    if [ "$DELAY" = "true" ]
    then
        sleep 15
    fi
 
    # We are finished, so call the cleanup crew.
    cleanup ""
else
    RFLAG=1
    cleanup "\n'root' access is required to run the HP Deployment Utility for Linux.\n"
    RC=1
fi
# If we were called from a CD and a reboot is scheduled,
# we need to eject the CD.
[ -x /usr/bin/eject ] && EJECT=/usr/bin/eject
[ -x /bin/eject ] && EJECT=/bin/eject
if [ ${#CDDEV} -gt 0 -a $RC -eq 16 ]
then
    cat >/tmp/eject.sh << []
kill -9 $$
cd /root
sleep 10
$EJECT -r $CDDEV
sleep 2
/bin/rm -f /tmp/eject.sh
exit

[]
    chmod 700 /tmp/eject.sh
    nohup /tmp/eject.sh >/dev/null 2>&1 &
    disown %nohup
fi
# echo $RC >rc.out
cd
exit $RC

