#!/bin/bash

LogFile=/tmp/HmcInstall.log

#-------------------------------------------------------------------------------
# Common exit point
#-------------------------------------------------------------------------------
function ExitCleanup {
    # keep the log file, but ensure a different user can overwrite it next time
    cd /
    chmod 666 $LogFile

    if [ $1 -ne 0 ]; then
        exit $1
    else
        exit 0
    fi
}

#-------------------------------------------------------------------------------
# This function does the RPM installation task.
#-------------------------------------------------------------------------------
function InstallRpm {
    if [ -f /opt/hsc/data/config/NO_UPDATE_RPMS ]; then
        x="$2"
        # Strip version then leading directory name
        f=`echo ${x%%-[0-9]*}`
        r=`echo ${f##*/}`
        for i in `cat /opt/hsc/data/config/NO_UPDATE_RPMS`; do
            if [ "$r" == "$i" ]; then
                return
            fi
        done
    fi

    CMD=`echo $1`; shift;
    RPM=`echo $1`; shift;
    OPT=`echo $*`
    OPT="$OPT --force --nodeps"

    # Log the test install output. The format for the "normal" RPM install
    # processing inside this script is 'rpm -i <file spec> --force --nodeps'
    if [ -f $RPM ]; then
        echo "=====================================================" >> $LogFile
        echo "***** Executing rpm -vv $CMD $RPM $OPT *****         " >> $LogFile
        echo "=====================================================" >> $LogFile
        rpm -vv $CMD $RPM $OPT >> $LogFile 2>&1
        if [ $? -ne 0 ]; then
            echo "Error installing rpm fileset named $2" >> $LogFile
            if [ "$Update" == "true" ]; then
                echo "Error installing rpm fileset named $2"
                ExitCleanup 9
            fi
        fi
    fi
}

#-------------------------------------------------------------------------------
# This function does the RPM removal task.
#-------------------------------------------------------------------------------
function EraseRpm {
    # If rpm is part of no update list then do not do anything with it
    if [ -f /opt/hsc/data/config/NO_UPDATE_RPMS ]; then
        x="$2"
        for i in `cat /opt/hsc/data/config/NO_UPDATE_RPMS`; do
            if [ "$x" == "$i" ]; then
                return
            fi
        done
    fi
    echo "=====================================================" >> $LogFile
    echo "***** Executing rpm -evv $* *****                    " >> $LogFile
    echo "=====================================================" >> $LogFile
    rpm -evv $* --nodeps --allmatches >> $LogFile 2>&1
    if [ $? -ne 0 ]; then
        echo "Error removing rpm fileset named $2" >> $LogFile
    fi
}

#-------------------------------------------------------------------------------
# This function Updates if already installed, else it installs
#-------------------------------------------------------------------------------
function RsctInstall {
    rpm -q $1 1>&2 2>/dev/null
    if [ $? -eq 0 ]; then
        InstallRpm -Uvh $2
    else
        InstallRpm -ivh $2
    fi
}

#-------------------------------------------------------------------------------
# This function installs patches that are not in rpms
#-------------------------------------------------------------------------------
function InstallPatch {
    FILE=`echo $1`; shift;
    MESG=`echo $*`
    if [ -f $FILE ]; then
        echo "--- Installing ${MESG}...." 
        cd /
        tar -xf $FILE
        if [ $? -ne 0 ]; then
            ExitCleanup 3
        fi
    fi
}

#-------------------------------------------------------------------------------
# Start the product install...
#-------------------------------------------------------------------------------
cd /
image=$1

if [ "$image" == "" ]; then
    echo "Please specify directory containing installable packages"
    echo "usage: installImages  <directory>"
    ExitCleanup 1
fi

# Check if directory exists
if [ ! -d $image ]; then
    echo "The directory $patchdir doesn't exist"
    echo "Please specify directory containing the installable packages."
    ExitCleanup 2
fi

PATH=$PATH:/opt/IBMJava/jre/bin:
LD_LIBRARY_PATH=/opt/hsc/lib:/opt/hsc/lib/hcmjni:/lib:/usr/lib:$LD_LIBRARY_PATH
export PATH LD_LIBRARY_PATH
migration_needed=0


cd $image

# Remove the zip file to save space
rm -f /usr/local/hsc_install.images/*.zip

# Save old log files
if [ -f $LogFile ]; then
    mv -f ${LogFile}.3 ${LogFile}.4 2>/dev/null
    mv -f ${LogFile}.2 ${LogFile}.3 2>/dev/null
    mv -f ${LogFile}.1 ${LogFile}.2 2>/dev/null
    mv -f ${LogFile}   ${LogFile}.1 2>/dev/null
fi

cp -f /opt/hsc/data/version /tmp/.version.orig

# requirement for installing Update images
if [ -f $image/.require ]; then
    /opt/hsc/bin/hsc version > /tmp/.version
    INSTALL="true"
    VERSION=`cat $image/.require | cut -d '|' -f 1`
    RELEASE=`cat $image/.require | cut -d '|' -f 2`

    grep -q "$VERSION" /tmp/.version
    if [ $? -ne 0 ]; then
        INSTALL="false"
    else
        if [ "$RELEASE" != "" ]; then
            grep -q "$RELEASE" /tmp/.version
            if [ $? -ne 0 ]; then
                INSTALL="false"
            fi
        fi
    fi

    if [ "$INSTALL" == "false" ]; then
        echo "Installation of this update image requires HMC $VERSION $RELEASE"
        echo "Current HMC is not $VERSION $RELEASE"
        echo "Unable to install this update image."
        ExitCleanup 3
    fi
fi

# check and install ptf-req rpm
if [ -f $image/IBMhmc.MH0*rpm ]; then
    cd $image
    PTF=`ls IBMhmc.MH0*rpm | cut -d '.' -f 2 | cut -d '_' -f 1`
    PTF_d=`rpm -qpl IBMhmc.MH0*rpm | grep MH0`
    if [ -f /opt/hsc/data/ptf/${PTF}_obs ]; then
        echo "--- Install error: This fix is now obsolete.  "
        ExitCleanup 3
    else
        echo "--- Installing ptf-req ...."
        rpm --force -Uvh IBMhmc.${PTF}*rpm >> $LogFile 2>&1
        if [ $? -ne 0 ]; then
            echo "--- Install error: failed dependencies"
            ExitCleanup 3
        else
            PTFdesc=`rpm -qpic IBMhmc.MH0*rpm | grep "$PTF:"`

            # remove ptf-req if it's 1st part(s) of an Update "_z1", "_d1", or "_d2"
            PTFREQ=`rpm -qpR IBMhmc.${PTF}*.rpm | grep ${PTF} | cut -d '=' -f 1`
            PTFupd=`echo ${PTFREQ} | cut -d '_' -f 2`
            if [[ "$PTFupd" == "z1" || "$PTFupd" == "d1" || "$PTFupd" == "d2" ]]; then
                rpm -e --nodeps ${PTFREQ}
            fi
        fi
    fi
fi


echo "=========================================================" >> $LogFile
disk=`cat $image/.signature | cut -d' ' -f 4`
if [[ "$disk" == "0" || -f $image/.image.updates ]]; then
    Update="true"
    echo "*********   Performing Update operation `date`  *********" >> $LogFile
else
    Update="false"
    echo "*********   Performing Install operation `date` *********" >> $LogFile
fi
echo "=========================================================" >> $LogFile

# Install RMC and CSM if rmc directory exists
if [ -d $image/rmc ]; then
    cd $image/rmc
    echo "--- Installing LPARCMD ...."
    RsctInstall hsc.lparcmd     hsc.lparcmd*.rpm 
fi


#
if [ -f $image/postinstall ]; then
    $image/postinstall
fi

if [ -f $image/.VERSION ]; then
    if [ -f $image/.dev ]; then
        cat $image/.VERSION >> /opt/hsc/data/version
    fi
    cat $image/.VERSION > /root/.version
    cat $image/.VERSION > /home/hscroot/.version
    chmod 644 /home/hscroot/.version
    chown hscroot.hmc /home/hscroot/.version
fi

if [ "$PTF" != "" ]; then
   # if this PTF installed before, remove its desc
   grep -q "$PTF" /tmp/.version.orig
   if [ $? -eq 0 ]; then
   # If there is a coreserver present then the /opt/hsc/data/version
   # file should not be overwritten
   # otherwise it is ok to do the next line
      if [ /opt/hsc/data/version -nt /tmp/.version.orig ]; then
      # remove PTF info from /opt/hs/data/version
         grep -q "$PTF" /opt/hsc/data/version
         if [ $? -eq 0 ]; then
            grep -v "$PTF" /opt/hsc/data/version  > /tmp/_version_old_
            cp -p /tmp/_version_old_ /opt/hsc/data/version
         fi
      else
        grep -v "$PTF" /tmp/.version.orig > /opt/hsc/data/version
      fi
   fi
fi

# for service pack, no need to display PTF description
if [ "$PTFdesc" != "" ]; then
   echo "$PTFdesc" >> /opt/hsc/data/version
fi

# indicate if this ptf requires another ptf
if [ "$PTF_d" != "" ]; then
    REQUIRE=`cat ${PTF_d} | grep REQUIRE | cut -d ':' -f 2`
    if [ "$REQUIRE" != "NONE" ]; then
        echo "*** The following package is a requisite of this installation:"
        echo "*** ${REQUIRE}"
        echo "*** Please apply the above requisite to complete this installation."
    fi
fi

echo "==========================================================" >> $LogFile
echo "********* Install/Update complete at `date` *********"      >> $LogFile
echo "==========================================================" >> $LogFile
ExitCleanup 0
