#!/bin/bash
#==============================================================================
## %PS
##
## Licensed Internal Code - Property of IBM
##
## 2105/2107 Licensed Internal Code
##
## (C) Copyright IBM Corp. 2004 All Rights Reserved.
##
## US Government Users Restricted Rights - Use, duplication or
## disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
## %EPS
##
## Filename: niAgentState.sh
##
## Subsystem: ESSNI
##
## Description: This script will enable and disable the essni processes
##
##
## Change History:
##   Modifier                   Date                            Change ID
##   ====================================================================
##   Amy Therrien          01-Oct-2004    110882
##      Initial Creation
##   Joseph Gimness        02-Dec-2004    121897
##      Update for separate DS6000 / DS8000 startup
##   Viorel Ciurea         15-Jan-2005
##      Update for support DS6000 Full/Offline mode startup
##   Constantin Simona     22-Jul-2005
##      Update for support MCP 
##   pjennas               03-Aug-2007
##      need to define com.ibm.storage.ess.ni.licversion
##   Yun Yuan              04-Dec-2008      224147
##      Remove ibmjsse.jar from classpath
##============================================================================

#
# Init file for DS Network Interface Server 
#
# chkconfig: 345 98 02
# description: DS Network Interface Server 
# 
### BEGIN INIT INFO
# Provides:          ESSNI 
# Required-Start:    
# Should-Start: 
# Required-Stop:      
# Should-Stop: 
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description:  DS Network Interface Server 
### END INIT INFO

function what_system(){
 if which rpm 2>/dev/null 1>/dev/null; then
  if rpm -q aaa_base 2>/dev/null 1>/dev/null; then
   SuSE=on
  elif rpm -qa | grep -v grep | grep redhat 2>/dev/null 1>/dev/null; then
   RedHat=on
  fi
 fi
}

what_system
# source function library
if [ ! -z "$RedHat" ]; then
.  /etc/rc.d/init.d/functions
elif [ ! -z "$SuSE" ]; then
.  /etc/rc.status
rc_reset
fi

function report_status(){
  if [ ! -z "$SuSE" ]; then 
   rc_failed $1
   rc_status -v
   rc_exit
  else
   # 0 - service running
   # 3 - service not running
   # 4 - service error 
   if [ $1 -eq 0 ]; then
     echo "is running ..."
   elif [ $1 -eq 3 ]; then
     echo "is stopped ..."
   else 
     echo "unknown ..."
   fi
  fi
  exit $1 
}

function report(){
  if [ ! -z "$SuSE" ]; then 
    rc_failed $1
    rc_status -v
    rc_exit
  elif [ ! -z "$RedHat" ];then
    if [ $1 -eq 0 ]; then
      [ "$2" == "start" ] && touch /var/lock/subsys/dsnisrv 
      [ "$2" == "stop" ]  && rm -rf /var/lock/subsys/dsnisrv 
      success 
      echo 
      exit 0
    else
      [ "$2" == "start" ] && rm -rf /var/lock/subsys/dsnisrv 
      failure
      echo 
      exit 1
    fi
  else
    if [ $1 -eq 0 ]; then
      echo "done"
    else
      echo "failure"
    fi
    exit $1
  fi
}


DSNI_HOME=%[DSNI_HOME]%
JAVA_HOME=${DSNI_HOME}/java/jre/bin
LOGFILE=${DSNI_HOME}/logs/srvlog.log
PID_FILE=/var/run/dsni.pid
prog="DS Network Interface"

areYouRoot(){
  currentID=$(id -u)
  rootID=$(id -u root)
  if [ $currentID -eq $rootID ];then
    return 0 
  else
    return 1 
  fi
}
kill_dsni(){
  startTime=$(date +"%s")
  elapsedTime=0
  not_killed=$(ps -ef --columns 10000 | grep -v grep | grep ESSNIServer.jar | awk '{print $2}')
  while [ ! -z "$not_killed" -a $elapsedTime -lt 60 ];do 
    pids=$not_killed;
    for PID in $pids; do 
      if ps -f --columns 10000 -p $PID | grep -v grep | grep ESSNIServer.jar > /dev/null; then
        childs=$(ps -e --format "%P %p" | grep -v grep | grep -E "^[[:space:]]*$PID ") 
        if [ -z "$childs" ]; then 
          kill -TERM $PID 2>/dev/null; 
          usleep 500
        fi
      fi
    done
    not_killed=$(ps -ef --columns 10000 |grep -v grep | grep ESSNIServer.jar|  awk '{print $2}')
    let elapsedTime=$(date +"%s")-$startTime
  done
  
  if [ $elapsedTime -gt 60 ]; then
    for PID in $not_killed; do
      if ps -f --columns 10000 -p $PID | grep -v grep | grep ESSNIServer.jar > /dev/null; then
        kill -9 $PID 2>/dev/null;
        usleep 500
      fi
    done
  fi
     
}

isDSNIRunning(){
   if ps -e -f --columns 10000 | grep -v grep | grep ESSNIServer.jar > /dev/null; then
    return 0 
   else
    return 1
   fi
}

start(){
  if ! areYouRoot; then
    echo "You must be root to run this command"
    exit 1
  fi
  echo -n "Starting $prog:"
  #first check whether DS Network Interface is not already running
  if isDSNIRunning; then
  report 0 "start"
  else
    cd ${DSNI_HOME} 
    LOGDIR=$(dirname $LOGFILE)
    if [ ! -d $LOGDIR ]; then
      mkdir -p $LOGDIR
    fi 


    #Start of modifications for support DS6000 Full/Offline mode startup
    #Look for the etc/DS6000Mode.properties file
    grep -i -E "^ *DS6000Mode=offline *$" etc/DS6000Mode.properties >/dev/null 2>/dev/null
    if [ $? -eq 0 ]; then
      DSMode=0
    else
      grep -i -E "^ *DS6000Mode=full *$" etc/DS6000Mode.properties >/dev/null 2>/dev/null
      if [ $? -eq 0 ]; then
        DSMode=1
      else
        #The etc/DS6000Mode.properties file not found, look for the DS6000 key in VPD
        grep -E "^ibmdsstoragemanager6000\|" ~root/vpd.properties >/dev/null 2>/dev/null
        if [ $? -ne 0 ]; then
          DSMode=0
        else
          DSMode=1
        fi
      fi
    fi
    if [ $DSMode -eq 0 ]; then
      #The invocation for DS8000 or DS6000 Ofline mode
      setsid "${JAVA_HOME}/java" -classpath lib/db2j.jar:lib/ESSNIServer.jar:lib/rmcapi.jar:lib/logger.jar:lib/hwmcaapi.jar:lib -Dcom.ibm.storage.ess.ni.licversion=etc/SEA.README -Dcom.ibm.storage.ess.ni.agent.properties=NIOfflineAgent.properties -Dcom.ibm.storage.ess.ni.logging=etc/niExternalServerLogging.properties -Dcom.ibm.storage.ess.ni.olc.logging=etc/niExternalOfflineLogging.properties -DRoutingTableFileProperty=etc/MessageRouterRoutingInformation.txt -Ddb2j.system.home=etc/db2j_system/ -Xms128M -Xmx256M  -Ddb2j.storage.pageSize=8192 -Ddb2j.storage.pageCacheSize=160 com.ibm.storage.ess.ni.server.NIESSNIServer 2>$LOGFILE 1>$LOGFILE &
    else
      #The invocation for DS6000 Full mode
      setsid "${JAVA_HOME}/java" -classpath lib/db2j.jar:lib/ESSNIServer.jar:lib/rmcapi.jar:lib/logger.jar:lib/hwmcaapi.jar:lib -Dcom.ibm.storage.ess.ni.licversion=etc/SEA.README -Dcom.ibm.storage.ess.ni.agent.properties=NIExternalAgent.properties -Dcom.ibm.storage.ess.ni.logging=etc/niExternalServerLogging.properties -Dcom.ibm.storage.ess.ni.olc.logging=etc/niExternalOfflineLogging.properties -DRoutingTableFileProperty=etc/MessageRouterRoutingInformation.txt -Ddb2j.system.home=etc/db2j_system/ -Xms128M -Xmx256M  -Ddb2j.storage.pageSize=8192 -Ddb2j.storage.pageCacheSize=160 com.ibm.storage.ess.ni.server.NIESSNIServer 2>$LOGFILE 1>$LOGFILE &
    fi
    #End of modifications for support DS6000 Full/Offline mode startup


    sleep 10
    if ps -f -e --columns 10000  | grep -v grep |  grep ESSNIServer.jar >/dev/null;then
   report 0 "start"
    else
   report 1 "start"
    fi
  fi
}
  
       
stop(){
  if ! areYouRoot; then
    echo "You must be root to run this command"
    exit 1
  fi
  echo -n "Stopping $prog:"
  if kill_dsni;then
  report 0 "stop"
  else
  report 1 "stop"
  fi
} 


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    try-restart)
        ## Stop the service and if this succeeds (i.e. the 
        ## service was running before), start it again.
        if ! areYouRoot; then
          echo "You must be root to run this command"
          exit 1
        fi
        $0 status >/dev/null &&  $0 restart
        ;;
    restart|force-reload|reload)
        ## Stop the service and regardless of whether it was
        ## running or not, start it again.
        if ! areYouRoot; then
          echo "You must be root to run this command"
          exit 1
        fi
        $0 stop
        $0 start
        ;;
    status)
        echo -n "Checking for DS Network Interface Server: "

        # 0 - service running
        # 3 - service not running
        if isDSNIRunning; then
     report_status 0
        else
     report_status 3 
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
        exit 1
        ;;
esac

