#!/bin/sh

#
# This script is executed before the patch is applied
#
#
#################################################################################
# Exit codes for installation scripts 
#################################################################################

e_ok=0	       # script completed successfully.
e_fatal=1      # stop installation on this exit
e_warning=2    # Installation will go on. 
e_int=3        # Interrupted. Stop installation
e_reboot=10    # User must reboot after installation of all selected packages
               # To be added to one of the single-digit exit code above
e_rebootnow=20 # User must reboot right after installation of current package
               # To be added to one of the single-digit exit code above
# Trap interrupt
trap `exit $e_int` 15

MYNAME=`basename $0`

GREP_CMD="/bin/grep"

#Name of the Calendar package
PKG="SUNWics5"

#Calendar Base directory
BASEDIR=`pkgparam -R $ROOTDIR SUNWics5 BASEDIR`

#Root directory
PKG_INSTALL_ROOT="$ROOTDIR"
if [ "$PKG_INSTALL_ROOT" = "/" ]; then
  PKG_INSTALL_ROOT=""
fi

# Config file
CONFIG_FILE=$PKG_INSTALL_ROOT$BASEDIR/$PKG/cal/config/ics.conf

#Counts the number of process running
NB_RUNNING_PROCESSES=`ps -ef|grep $PKG_INSTALL_ROOT$BASEDIR/$PKG/cal|grep -v grep|wc -l|tr -d ' '`

if [ $NB_RUNNING_PROCESSES -gt 0 ]
then
  if [ -f $CONFIG_FILE ]
  then
    # Check for HA settings in the config file
    HA_ENABLED=`$GREP_CMD '^local.server.ha.enabled' $CONFIG_FILE | tail -1| cut -d"=" -f2 | sed "s/\"//g" | sed "s/^ *//" | sed "s/ *$//"`
    HA_AGENT=`$GREP_CMD '^local.server.ha.agent' $CONFIG_FILE | tail -1| cut -d"=" -f2 | sed "s/\"//g" | sed "s/^ *//" | sed "s/ *$//"`

    if [ "$HA_ENABLED" != "yes" -a HA_AGENT != "SUNWscics" ]
    then
      # If it not HA we can stop the service safely
      echo "Shutting down the services"
      cd $PKG_INSTALL_ROOT$BASEDIR/$PKG/cal/sbin
      $PKG_INSTALL_ROOT$BASEDIR/$PKG/cal/sbin/stop-cal
    else
      echo "There is currently $NB_RUNNING_PROCESSES Calendar Server process(es) running."
      echo "All services must be shutdown in order to process."
      echo "Please shutdown every services, and try again."
      exit $e_fatal
    fi
  else
    echo "Cannot find the product configuration file $CONFIG_FILE"
    exit "$e_fatal"
  fi
fi

exit $e_ok
