fatal () {
    echo "$*" >&2
    exit 1
}

# Check for root
#
user=`/bin/id | /usr/bin/grep root | /usr/bin/wc -l`
if [ $user -eq 0 ]; then
    fatal "You must be root to run this script."
fi


# Setup the ESM environment if not running under esmpatch
#
if [ "$ESM_CONTEXT" != "patch" ]; then

    ESM_BASE=`/usr/bin/pkgparam SUNWstm ESM_BASE`
    if [ $? -ne 0 ]; then
        fatal "Could not determine ESM location!"
    fi

    . $ESM_BASE/lib/esm_env.sh
fi


# --------------------------------------------------------------------
# Update the Service Tier Container (IH)
#
ESM_IH_HOME=$ESM_PLATFORM/ih
TOMCAT_HOME=$ESM_IH_HOME/jakarta-tomcat-4.0.6-LE-jdk14
IHAPP=$ESM_IH_HOME/esmih.war
OLDIHAPP=$IHAPP.old.tar

# Ensure the old tarred/compressed version of the Container (IH)
# exists for use in postbackout.
#
if [ ! -f $OLDIHAPP.Z ] ; then
    fatal "Unable to locate the previous version of the Container app ($OLDIHAPP.Z)"
fi

# Remove the patched version of the Container, then restore
# the old tarred/compressed version.
#
if cd $TOMCAT_HOME/webapps            &&
   /usr/bin/rm -rf esmih              &&
   /usr/bin/mkdir esmih               &&
   cd esmih                           &&
   /usr/bin/uncompress -f $OLDIHAPP.Z &&
   /usr/bin/tar xof $OLDIHAPP
then
    /usr/bin/rm $OLDIHAPP
else
    fatal "Failure to install the new Container web application"
fi


# --------------------------------------------------------------------
# Restore the UI Lockart web application
#
PT_APPNAME='com.sun.netstorage.mgmt.ui.framework_1.0'
PT_APPDIR=$ESM_PLATFORM/smicc/frameworkweb
PT_APPWAR=$ESM_PLATFORM/smicc/frameworkweb.war
OLDUIAPP=$PT_APPWAR.old.tar

# Ensure the old tarred/compressed version of the UI web app
# exists for use in postbackout.
#
if [ ! -f $OLDUIAPP.Z ] ; then
    fatal "Unable to locate the previous version of the Capacity Reporter web app ($OLDUIAPP.Z)"
fi

# Unregister the patched version of the UI web app, delete the
# web app tree, then restore the old version and re-register it
# with Lockhart.
#
if /usr/sbin/smreg remove -a "$PT_APPNAME" ; then

    if /usr/bin/rm -rf $PT_APPDIR         &&
       /usr/bin/mkdir $PT_APPDIR          &&
       cd $PT_APPDIR                      &&
       /usr/bin/uncompress -f $OLDUIAPP.Z &&
       /usr/bin/tar xof $OLDUIAPP
    then
	/usr/sbin/smreg add -a $PT_APPDIR ||
	    fatal "Failure to register the Capacity Reporter smcwebserver application!"

        /usr/bin/rm $OLDUIAPP
    else
	fatal "Failure to unregister the patched Capacity Reporter smcwebserver application!"
    fi
fi


# --------------------------------------------------------------------
# Start ESM and Lockhart if not running as part of esmpatch
#
if [ "$ESM_CONTEXT" != "patch" ]; then

    SWCSERVER=/usr/sbin/smcwebserver
    if [ -f "$SWCSERVER" ]; then
        $SWCSERVER start
    else
        fatal "Unable to start $SWCSERVER"
    fi

    $ESM_BASE/bin/esmcontrol start
fi

exit 0
