#!/bin/sh

#
# This script is executed before the patch is backed out
#
#
#################################################################################
# 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`

LS="/bin/ls"
RM="/bin/rm"
LN="/bin/ln"
WC="/bin/wc"
TR="/bin/tr"
AWK="/bin/awk"
NAWK="/bin/nawk"
SED="/bin/sed"
CUT="/bin/cut"
ECHO="/bin/echo"
GREP="/bin/grep"
CHOWN="/bin/chown"
SORT="/bin/sort"
HEAD="/bin/head"
TAIL="/bin/tail"
PKGPARAM="/bin/pkgparam"
UNAME="/bin/uname"

#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

#Calendar Config directory
CS_CONFIG_DIR="$PKG_INSTALL_ROOT$BASEDIR/$PKG/cal/config"

#Calendar config file
CS_CONFIG_FILE="$CS_CONFIG_DIR/ics.conf"

if [ -h $CS_CONFIG_DIR ]; then
  linktarget=`$LS -l $CS_CONFIG_DIR | $NAWK -F'-> ' '{print $2}'`
  CS_CONFIG_FILE="$ROOTDIR$linktarget/ics.conf"
fi

if [ -z "$PKG_INSTALL_ROOT" ] 
then
  #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 $CS_CONFIG_FILE ]
    then
      # Check for HA settings in the config file
      HA_ENABLED=`$GREP '^local.server.ha.enabled' $CS_CONFIG_FILE | tail -1| cut -d"=" -f2 | sed "s/\"//g" | sed "s/^ *//" | sed "s/ *$//"`
      HA_AGENT=`$GREP '^local.server.ha.agent' $CS_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 $CS_CONFIG_FILE"
      exit "$e_fatal"
    fi
  fi
fi

exit $e_ok
