#!/bin/sh
#
# Copyright 1999-2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
# 

# usage
usage () {
  echo "Usage: imadmin [options] start|refresh|stop|version|migrate|check [service]"
  echo ""
  echo "  options: -c <config-file> - absolute path to configuration file"
  echo "           -h               - print help"
  echo ""
  echo "  service: server | multiplexor | watchdog | agent-calendar"
  echo "           multiplexor      - multiplexor only"
  echo "           server           - server only"
  echo "           watchdog         - watchdog only"
  echo "           agent-calendar   - IM Calendar agent only"
  echo ""
  exit 1
}

# Getting the OS name (SunOS or Linux)
OS="`/bin/uname -s`"

# Terminal columns
if [ "$TERM" = "" ]; then
  TERM=vt100
fi
TPUT="tput -T $TERM"
COLS=`$TPUT cols`

# define utilities and how to reach them
# OS-specific section 
if [ "$OS" = "Linux" ]; then
  ID=/usr/bin/id
  ECHO="echo -n"
  ECHO_END=""
else
  ID=/bin/id
  ECHO="echo"
  ECHO_END="\c"
fi
PATH=/usr/bin:/bin:$PATH

#
# Get pid from pidfile
# Assumes file contains pid as first line
getPid() {
  head -n 1 $1 2>/dev/null
}

# get a variable's value from config file.
getValue() {
 y=`egrep "$1 *=" $config_file | tail -1l | grep -v '^!' | awk -F= '{print $2}' | tr -d '" '`
 echo $y
}

# checks if a pid in a pid file refers a running process
getStatus() {
  if [ -f $1 ]; then
    ps -p `getPid $1` > /dev/null 2>&1
    echo $?
  else
    echo 127
  fi
}

getLength() {
  expr `echo $1|wc -c|tr -d ' '` - 1
}

printState() {
  state=$1
  if [ "$state" = "OK" -o "$state" = "UP" -o "$state" = "RUNNING" ]; then
    if [ "$OS" = "Linux" ]; then
      start=`$TPUT setf 2`
    else
      start='\033[32m'
    fi
  else
    if [ "$OS" = "Linux" ]; then
      start=`$TPUT setf 4`
    else
      start='\033[31m'
    fi
  fi
  if [ "$OS" = "Linux" ]; then
    end=`$TPUT sgr0`
  else
    end='\033[0m'
  fi
  state="$start$state$end"
  echo $state
}

whiteSpaceFiller() {
  string=$1
  width=$2
  i=0
  while [ $i -lt $width ]; do
    string="$string "
    i=`expr $i + 1`
  done
  echo $string  
}

myEcho() {
    $ECHO $@ $ECHO_END
}

printScreenWidth() {
  module=$1
  state=$2
  width=$COLS
  rightMargin=2
  if [ $# -eq 3 ]; then
    width=`expr $width - \`getLength "$3"\``
  else
    myEcho $module
    width=`expr $width - \`getLength "$module"\` - 1`
  fi
  $TPUT cuf `expr $width - \`getLength $state\` - 2 - $rightMargin`
  echo "[`printState $state`]"
}

hourGlassStart() {
  $TPUT civis
  $TPUT hpa `expr $COLS - 1`
}

hourGlassRun() {
  position=$1
  case $position in
    0) hg="|";;
    1) hg="/";;
    2) hg="-";;
    3) hg="\\";;
  esac
  myEcho $hg
  $TPUT cub1
  position=`expr $position + 1`
  if [ $position -gt 3 ]; then
    position=0
  fi
  return $position
}

hourGlassStop() {
  $TPUT cnorm
}

stopProcess() {
    pidFile=$1
    status=`getStatus $1`
    pid=`getPid $1`
    keepLooping=10
    msg="Stopping $2"
    myEcho $msg
    if [ $status -eq 0 ]; then
      kill $pid
      while [ $keepLooping -gt 0 ]; do
        status=`getStatus $1`
        if [ $status -ne 0 ]; then
          keepLooping=0
        else
          sleep 1
        fi
        keepLooping=`expr $keepLooping - 1`
      done
      if [ $status -eq 0 ]; then
        kill -9 $pid
      fi
      printScreenWidth "" OK "$msg"
    else
      printScreenWidth "" FAILED "$msg"
      echo "$2 already stopped"
    fi
    rm -f $1
    return 0
}

waitFor() {
  pidfile=$1
  msg=$2
  status=128
  #position=0
  #hourGlassStart
  start=0
  TIMEOUT=10
  while [ $status -ne 0 -a  $start -lt $TIMEOUT ]; do
    status=`getStatus $pidfile`
    start=`expr $start + 1`
    sleep 1
    #hourGlassRun $position
    #position=$?
  done
  #hourGlassStop
  if [ $status -eq 0 ]; then
    state="OK"
  else
    state="TIMEOUT"
  fi
  printScreenWidth "" $state "$msg"
}

#
# Check a potential Java directory
#
chkJava() {
  javadir=$1
  if [ "$javadir" = "" ]; then
    # Not yet set..
    return 1
  elif /usr/bin/test \! -x $javadir/bin/java; then
    # Java command not found at $javadir/bin/java"
    return 2
  else
    # $javadir OK so far
    this_version=`$javadir/bin/java -version 2>&1 |head -1|awk '{print $3}' | \
	sed -e 's/"//g' | cut -d. -f1-2`
    if [ "$this_version" = "1.4" ] || [ "$this_version" = "1.5" ] || 
		[ "$this_version" = "1.6" ]; then
      return 0
    else
      # Too old a version
      return 3
    fi
  fi
}

#
# Hunt for a usable Java
#
findJava() {
  java_cmd=`getValue iim.jvm.command`
  java_dir=`echo $java_cmd|sed 's/\/bin\/java$//'`
  chkJava $java_dir
  if [ $? -ne 0 ]; then
    java_cmd=""
    # Check for the standard JES Java
    if /usr/bin/test -L /usr/jdk/entsys-j2se; then
      java_dir=/usr/jdk/entsys-j2se
      chkJava $java_dir
      if [ $? -eq 0 ]; then
        java_cmd=$java_dir/bin/java
	return 0
      fi
    fi
    # Nothing easy found, go hunting for Java RPMs/packages..
    if [ "$OS" = "Linux" ]; then
      java_versions=`rpm -q --all|egrep 'jdk|jre|j2se|j2re|j2sdk'`
      for v in $java_versions; do
        jv=`rpm -q -l $v|grep 'bin.java$'|head -1`
        jv=`echo $jv|sed 's/\/bin\/java$//'`
        if [ "$jv" != "" ]; then
          chkJava $jv
          if [ $? -eq 0 ]; then
            java_cmd=$jv/bin/java
	    java_dir=$jv
	    return 0
          fi
        fi
      done
    else
      # Solaris..
      # No easy hunting on Solaris, but something could be added here.
      # (Will fall through to the well-known locations, though.)
      :
    fi
    # Look in the current path
    java_cmd=`which java`
    if [ "$java_cmd" != "" ]; then
      java_dir=`echo $java_cmd|sed -e 's/bin\/java//'`
      chkJava $java_dir
      if [ $? -eq 0 ]; then
        return 0
      fi
    fi
    # Try JAVA_HOME environment variable
    if [ "$JAVA_HOME" != "" ]; then
      chkJava $JAVA_HOME
      if [ $? -eq 0 ]; then
        java_cmd=$JAVA_HOME
        java_dir=`echo $java_cmd|sed -e 's/bin\/java//'`
	return 0
      fi
    fi
    # Finally just try some well-known locations
    chkJava /usr/java
    if [ $? -eq 0 ]; then
      java_cmd=/usr/java/bin/java
      java_dir=/usr/java
      return 0
    fi
    chkJava /usr/j2se
    if [ $? -eq 0 ]; then
      java_cmd=/usr/j2se/bin/java
      java_dir=/usr/j2se
      return 0
    fi
  else
    return 0
  fi
  # finally check for any "internal" java to the installation..
  chkJava $installdir/java/jre
  if [ $? -eq 0 ]; then
    java_cmd=$installdir/java/jre/bin/java
    java_dir=$installdir/java
    return 0
  fi
  return 1
}

# Define default parameters
#
cmd=""
admindir="."

IIMUSER="inetuser"
USER=2


# get basic OS info, set OS-specific commands
FROM_RPM=0
if [ "$OS" = "Linux" ]; then
  # Prevent .bashrc reading problems when calling su
  export BASH_ENV=""
  if [ ${RPM_INSTALL_PREFIX} ]; then
    FROM_RPM=1
  fi
fi

# find path
cmd_path=$0
admindir=`dirname $cmd_path`
#Changing the dir to sbin so that the mux can get the lib directory.
cd ${admindir}
admindir="."
installdir=$admindir/..
sleep_interval=10

config_dir=$installdir/config
config_file=$config_dir/iim.conf
server_pid=""

# get options
#
while getopts hc: opts ; do
        case "${opts}" in
		h ) usage ;;
		c ) config_file=${OPTARG} ;;
                * ) continue ;;
	esac
done
shift `expr ${OPTIND} - 1`

#Make sure there is some command
#
if [ $# -lt 1 ]; then
  usage
fi

if [ ! -r $config_file ]; then
  # Be quiet about the error if running from RPM
  if [ $FROM_RPM != 1 ]; then
    echo "Configuration file $config_file is missing, exiting"
  fi
  exit 1
fi

watchdog_enabled=1
server_enabled=1
multiplexor_enabled=1
agents_enabled=1

if [ "$OS" = "Linux" ]; then
  # product class dir
  PCD=$installdir/lib
  # product library dir
  PLD=$installdir/lib
  # product public library dir
  PPuLD=$installdir/share/lib
  # product private library dir
  PPrLD=$installdir/private/share/lib
  # shared component private dir
  SCPrD=/opt/sun/private/share/lib
  # shared component public dir
  SCPuD=/opt/sun/share/lib
  # first choice for 4ss dir
  JSSD1=/usr/share/lib/mps/secv1
  # second choice for jss dir
  JSSD2=/opt/sun/private/share/lib
  JDMKD=/opt/sun/jdmk/5.1/lib
  MFWKD=/opt/sun/mfwk/lib
  MFWKJ1=/opt/sun/mfwk/share/lib
  MFWKJ2=/opt/sun/mfwk/private/share/lib
else
  PCD=$installdir/lib
  PLD=$installdir/lib
  PPrLD=$installdir/lib
  SCPuD=/usr/share/lib
  SCPrD=/usr/share/lib/xmpp
  PPuLD=$installdir/share/lib
  JSSD1=/usr/share/lib/mps/secv1
  JSSD2=/usr/share/lib/mps
  JDMKD=/opt/SUNWjdmk/5.1/lib
  MFWKD=/opt/SUNWmfwk/lib
fi

#
# Hunt for a usable Java
#
findJava
if [ $? -ne 0 ]; then
  echo No suitable Java found, exiting
fi

# security .so libs
if [ "$OS" = "Linux" ]; then
  SEC_LIB_PATH=/opt/sun/private/lib:$java_dir/jre/lib/i386/native_threads:${SEC_LIB_PATH}
  JSS_JAR=${JSSD1}/jss4.jar
  if  [ ! -f $JSS_JAR ]; then
    JSS_JAR=${JSSD2}/jss4.jar
    if [ ! -f $JSS_JAR ]; then
      JSS_JAR=${installdir}/lib/jss4.jar
      if [ ! -f $JSS_JAR ]; then
	JSS_JAR=${JSSD1}/jss3.jar
	if  [ ! -f $JSS_JAR ]; then
	  JSS_JAR=${JSSD2}/jss3.jar
	  if [ ! -f $JSS_JAR ]; then
	    JSS_JAR=${installdir}/lib/jss3.jar
	  fi
	fi
      fi
    fi
  fi
else
  SEC_LIB_PATH=/usr/lib/mps/secv1:/usr/lib/mps
  JSS_JAR=${JSSD1}/jss4.jar
  if [ ! -f $JSS_JAR ]; then
    JSS_JAR=${JSSD2}/jss4.jar
    if [ ! -f $JSS_JAR ]; then
      JSS_JAR=${installdir}/lib/jss4.jar
      if [ ! -f $JSS_JAR ]; then
	JSS_JAR=${JSSD1}/jss3.jar
	if [ ! -f $JSS_JAR ]; then
	  JSS_JAR=${JSSD2}/jss3.jar
	  if [ ! -f $JSS_JAR ]; then
	    JSS_JAR=${installdir}/lib/jss3.jar
	  fi
	fi
      fi
    fi
  fi
fi

JAXP_JARS=${SCPuD}/jaxp-api.jar:${SCPuD}/xalan.jar:${SCPuD}/xercesImpl.jar:${SCPuD}/sax.jar:${SCPuD}/dom.jar:${SCPuD}/xsltc.jar

JDMK_JARS=$JDMKD/jmx.jar:$JDMKD/jmxremote.jar:$JDMKD/jmxremote_optional.jar:$JDMKD/jdmkrt.jar
if [ "$OS" = "Linux" ]; then
  MFWK_JARS=$MFWKJ1/mfwk_sdk.jar:$MFWKJ1/rmi2rpc.jar:$MFWKJ2/xml-apis.jar:$MFWKJ2/javax77.jar:$MFWKJ2/jdom.jar:$MFWKJ2/xercesImpl.jar
else
  MFWK_JARS=$MFWKD/mfwk_sdk.jar:$MFWKD/rmi2rpc.jar:$MFWKD/xml-apis.jar:$MFWKD/javax77.jar:$MFWKD/jdom.jar:$MFWKD/xercesImpl.jar
fi

JSO_JARS=$SCPuD/jso.jar:$SCPuD/xp.jar:$SCPuD/log4j.jar:$SCPuD/jaxen-core.jar:$SCPuD/saxpath.jar

server_classpath=$MFWK_JARS:$JDMK_JARS:${JSS_JAR}:$SCPrD/xmppd.jar:$SCPrD/improvider.jar:$SCPuD/imservice.jar:$SCPuD/activation.jar:$SCPuD/mail.jar:$PCD/ens.jar:$PPrLD/jms.jar:$PCD/icalendar.jar:$PCD/suncalendar.jar:$PCD/searchsdk.jar:$PPrLD/ldapjdk.jar:$PCD/imidutil.jar:${JAXP_JARS}:${JSO_JARS}

watchdog_classpath=$MFWK_JARS:$JDMK_JARS:$SCPuD/imservice.jar:$SCPrD/xmppd.jar:${JSO_JARS}

agents_classpath=$server_classpath:$PCD/jms.jar

server_pid=""
execdaemon_cmd=${installdir}/lib/execdaemon
multiplexor_cmd=${installdir}/lib/multiplexor

# detect presence of identity from packages
id_installed=0;
if [ "$OS" = "Linux" ]; then
  rpm -q sun-identity-sdk > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    id_installed=1
    id_package="sun-identity-sdk"
  else
    rpm -q sun-identity-services > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      id_installed=1
      id_package="sun-identity-services"
    else
      rpm -q SUNWamsdk > /dev/null 2>&1
      if [ $? -eq 0 ]; then
        id_installed=1
        id_package="SUNWamsdk"
      else
        rpm -q SUNWamsvc > /dev/null 2>&1
        if [ $? -eq 0 ]; then
          id_installed=1
          id_package="SUNWamsvc"
	      fi
      fi
    fi
  fi
else
  pkginfo SUNWamsdk > /dev/null 2>&1
  if [ $? -eq 0 ]; then
      id_installed=1
      id_package="SUNWamsdk"
  fi
  pkginfo SUNWamsvc > /dev/null 2>&1
  if [ $? -eq 0 ]; then
      id_installed=1
      id_package="SUNWamsvc"
  fi
fi
  
if [ $id_installed -eq 1 ]; then
  #Do more verification for the usage of identity server.
  USESSO=`getValue iim_server.usesso`
  MODULE=`getValue iim.policy.modules`
  if [ "$USESSO" = "0" -a "$MODULE" != "identity" ]; then
    id_installed=0
  else
    if [ "$OS" = "Linux" ]; then
      id_basedir=`rpm -q --qf "%{INSTPREFIXES}" $id_package`
      if [ "$id_basedir" = "(none)" ]; then
        id_basedir=`rpm -q --qf "%{DIRNAMES}" $id_package`
        id_basedir=`dirname $id_basedir`
      fi

      AM_PROP_FILE="/etc/opt/sun/identity/config/AMConfig.properties"
      if [ ! -r $AM_PROP_FILE ]; then
        # Try falling back to IS6.1 location
        AM_PROP_FILE=${id_basedir}/SUNWam/lib/AMConfig.properties
      fi
    else
      id_basedir=`pkgparam -v $id_package |grep \^BASEDIR= | cut -f2 -d = |sed -e s/\'//g''` 
      AM_PROP_FILE="/etc/opt/SUNWam/config/AMConfig.properties"
      if [ ! -r $AM_PROP_FILE ]; then
	# Try falling back to IS6.1 location
	AM_PROP_FILE=${id_basedir}/SUNWam/lib/AMConfig.properties
      fi
    fi
    id_jre=`grep "jdk.path" $AM_PROP_FILE|cut -f2 -d=`
  fi
fi


# read some option from config file
if [ -f $config_file ]; then
  IIMUSER=`getValue iim.user`
  
  # max mem size argument
  maxmemsize=`getValue iim.jvm.maxmemorysize`
  if [ "$maxmemsize" = "" ]; then
    maxmemsize=256
  fi

  # disabled components
  val=`getValue iim_server.enable`
  case $val in
    [fF][aA][lL][sS][eE] | [nN][oO] )
        server_enabled=0
	;;
    * ) 
	;;
  esac
  
  val=`getValue iim_mux.enable`
  case $val in
    [fF][aA][lL][sS][eE] | [nN][oO] )
        multiplexor_enabled=0
	;;
    * ) 
	;;
  esac

  val=`getValue iim_wd.enable`
  case $val in
    [fF][aA][lL][sS][eE] | [nN][oO] )
        watchdog_enabled=0
	;;
    * ) 
	;;
  esac

  val=`getValue iim_agent.enable`
  case $val in
    [fF][aA][lL][sS][eE] | [nN][oO] )
        agents_enabled=0
        ;;
    * )
        ;;
  esac


  # identity sdk and jre locations
  val=`getValue iim.identity.basedir`
  if [ "$val" != "" ]; then
    id_installed=1
    id_basedir=$val
  fi
  val=`getValue iim.identity.jre`
  if [ "$val" != "" ]; then
    id_jre=$val
  fi

fi

# set local variables that are dependent from the configuration
vardir=`getValue iim.instancevardir`
logdir=${vardir}/log

# ## PID files definitions
# Server PID file
iimpidfile=`getValue iim.pidfile`
if [ "$iimpidfile" = "" ]; then
  iimpidfile="xmppd.pid"
fi
iimpidfile=${vardir}/log/$iimpidfile

# Watchdog PID file
wdpidfile=`getValue iim_wd.pidfile`
if [ "$wdpifile" = "" ]; then
  wdpidfile="wd.pid"
fi
wdpidfile=${vardir}/log/$wdpidfile

# Agents PID file
calimbot_logdir=${vardir}/log/
calimbot_pidfile=${vardir}/log/agent-calendar.pid

# Multiplexor PID file
muxpidfile=${vardir}/log/mux.pid

if [ "$OS" = "Linux" ]; then
  AM_HOME=${id_basedir}/identity
else
  AM_HOME=${id_basedir}/SUNWam
fi

if [ $id_installed -eq 1 ]; then
  SDK_JARS=${AM_HOME}/lib/am_sdk.jar:${AM_HOME}/lib/am_services.jar:${AM_HOME}/lib/am_logging.jar:${AM_HOME}/lib/jaas.jar:${AM_HOME}/lib/servlet.jar:${AM_HOME}/lib/preference_servlet.jar
  if [ "$OS" = "Linux" ]; then
    AM_CONFIG_DIR=/etc/opt/sun/identity/config
  else
    AM_CONFIG_DIR=/etc/opt/SUNWam/config
  fi
  AM_CLASSPATH=${AM_CONFIG_DIR}:${AM_HOME}/lib:${AM_HOME}/locale:${SDK_JARS}

  server_classpath=${AM_CLASSPATH}:${server_classpath}
  if [ "$id_jre" != "" ]; then
    chkJava $id_jre
    if [ $? -eq 0 ]; then
      java_cmd=$id_jre/bin/java
      java_dir=$id_jre
    fi
  fi
fi

# set environment
ADDLIBPATH=$MFWKD:$JDMKD:${installdir}/lib:${SEC_LIB_PATH}
LD_LIBRARY_PATH=${ADDLIBPATH}:${LD_LIBRARY_PATH}
export LD_LIBRARY_PATH

# Set the command to run
#
case $1 in
	[sS][tT][aA][rR][tT] )
	    cmd=start
	    ;;
	[sS][tT][oO][pP] | [sS][hH][uU][tT][dD][oO][wW][nN] )
	    cmd=stop
	    ;;
	[rR][eE][fF][rR][eE][sS][hH] )
	    cmd=refresh
	    ;;
	[vV][eE][rR][sS][iI][oO][nN] )
	    cmd=version
	    ;;
	[mM][iI][gG][rR][aA][tT][eE] )
	    cmd=migrate
	    ;;
	[sS][tT][aA][tT][uU][sS] | [cC][hH][eE][cC][kK])
	    cmd=status
	    ;;
	* ) echo "ERROR: Unknown command: $1"
	    echo
	    usage
	    ;;
esac


# Set the service to act upon
#
if [ $# -gt 1 ]; then
  case $2 in
  [iI][iI][mM] )
        ;;
  [lL][eE][gG][aA][cC][yY] )
        service=legacy
        ;;
  [wW][aA][tT][cC][hH][dD][oO][gG] )
        service=watchdog
        ;;
  [sS][eE][rR][vV][eE][rR] )
        service=server
        ;;
  [mM][uU][lL][tT][iI][pP][lL][eE][xX][oO][rR] )
        service=multiplexor
        ;;
  [iI][iI][mM]_[mM][uU][xX] )
        service=multiplexor
        ;;
  [iI][iI][mM]_[sS][eE][rR][vV][eE][rR] )
        service=server
        ;;
  [aA][gG][eE][nN][tT][:_-][cC][aA][lL][eE][nN][dD][aA][rR])
        service=calimbot
        ;;
	* )
        bypass=0
        secArg=`expr $2 \* 1 2>/dev/null`
        st=$?
        if [ $? -eq 0 ]; then
          if [ "$cmd"="status" -a "$2" = "$secArg" ]; then
            bypass=1
          fi
        fi
        if [ $bypass -eq 0 ]; then
          echo "ERROR: Unknown service: $2"
          echo
          usage
        fi
      ;;
  esac
fi


# Get the uid of the user executing this script
# and test whether it is IIM_USER,root or other
#
verifyUid() {
  my_uid=`$ID | cut -d '=' -f 2 | cut -d '(' -f 1 | tr -d ' '`
  IIMUID=`$ID $IIMUSER | cut -d '=' -f 2 | cut -d '(' -f 1 | tr -d ' '`
  if [ $my_uid  -eq 0 ]; then
    user_code=0
  elif [ $my_uid  -eq $IIMUID ]; then
    user_code=1
  else
    user_code=2
  fi

# If IIMUID itself is root, treat it as regular owner and don't try su.
  if [ $IIMUID -eq 0 ]; then
    user_code=1
  fi
}
  
# Migrate acl file to LDAP
migrate_acl() {
  if [ ! -d ${logdir} ]; then
    mkdir ${logdir}
  fi
  echo "Access control file migration starting"
  $java_cmd -Djava.awt.headless=true -cp $server_classpath -Djava.awt.headless=true -Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.protocol.handler.pkgs=com.iplanet.services.comm -Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Dcom.iplanet.coreservices.configpath=${AM_CONFIG_DIR}/config/ums com.iplanet.im.server.MigrateAcl -c $config_file 
  status=$?
  if [ $status -eq "0" ]; then
    grep -v "iim.policy.store" ${config_file} > ${config_file}.tmp
    echo "" >> ${config_file}.tmp
    echo "! Policy Store (identity or file)" >> ${config_file}.tmp
    echo "iim.policy.store=identity" >> ${config_file}.tmp
    mv ${config_file}.tmp ${config_file}
    echo "Migration successful."
  else
    echo "Migration failed with status $status"
  fi  

  return $status
}

# Start the watchdog
start_watchdog() {
  modName="Watchdog"
  if [ "$1" != "" ]; then
    prm=$1
  fi
  
  verifyUid
  if [ $user_code -eq 1 ]; then

    if [ ! -d ${logdir} ] ; then
      mkdir ${logdir}
    fi

    status=`getStatus $wdpidfile`
    msg="Starting $modName"
    if [ $status -eq 0 ]; then
      printScreenWidth "$msg" FAILED
      echo "$modName already running"
      status=10
    else
      myEcho $msg
      prevValue=$IIM_PIDFILE
      IIM_PIDFILE=${wdpidfile}
      export IIM_PIDFILE
      $execdaemon_cmd $java_cmd -Djava.awt.headless=true -cp $watchdog_classpath com.iplanet.im.server.Watchdog -c $config_file $prm&
      status=$?
      IIM_PIDFILE=$prevValue
      export IIM_PIDFILE
      waitFor $wdpidfile "$msg"
    fi
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file start watchdog \"$prm\""
    status=$?
  else
    echo "$modName can be started by root or $IIMUSER only"
    status=1  
  fi
  return $status
}

# Start the server
start_server() {
  modName="Server"
  verifyUid
  if [ $user_code -eq 1 ]; then
    if [ ! -d ${logdir} ]; then
      mkdir ${logdir}
    fi

    IIM_PIDFILE=${iimpidfile}
    export IIM_PIDFILE
    msg="Starting $modName"
    status=`getStatus $iimpidfile`
    if [ $status -eq 0 ]; then
      printScreenWidth "$msg" FAILED
      echo "$modName already running"
      status=10
    else  
      myEcho $msg
      if [ $id_installed = 1 ]; then
        $execdaemon_cmd $java_cmd -server -Xmx${maxmemsize}m -cp $server_classpath -Djava.awt.headless=true -Djava.protocol.handler.pkgs=com.iplanet.services.comm -Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Dcom.iplanet.coreservices.configpath=${AM_CONFIG_DIR}/config/ums com.iplanet.im.server.NMS -c $config_file -w 15 &
        status=$?
      else
        $execdaemon_cmd $java_cmd -Djava.awt.headless=true -server -Xmx${maxmemsize}m -cp $server_classpath com.iplanet.im.server.NMS -c $config_file -w 15 &
        status=$?
      fi
      waitFor $iimpidfile "$msg"
    fi
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file start server"
    status=$?
  else
    echo "$modName can be started by root or $IIMUSER only"
    status=1 
  fi
  return $status
}

# Start the multiplexor
start_multiplexor() {
  modName="Multiplexor"
  verifyUid
  if [ "$OS" = "Linux" ]; then
    ulimit -n 4096 > /dev/null 2>&1
  fi
  if [ $user_code -eq 1 ]; then
    msg="Starting $modName"
    status=`getStatus $muxpidfile`
    if [ $status -eq 0 ]; then
      printScreenWidth "$msg" FAILED
      echo "$modName already running"
      status=10
    else
      myEcho $msg
      $multiplexor_cmd -c $config_file&
      status=$?
      waitFor $muxpidfile "$msg"
    fi
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$multiplexor_cmd -c $config_file&"
    status=$?
  else
    echo "$modName can be started by root or $IIMUSER only"
    status=1 
  fi
  return $status
}


# Start the calender im bot
start_calimbot() {
  modName="agent-calendar"
  status=0
  verifyUid
  if [ $user_code -eq 1 ]; then
    if [ ! -d ${calimbot_logdir} ]; then
      mkdir ${calimbot_logdir}
    fi

    status=`getStatus $calimbot_pidfile`
    msg="Starting $modName"
    if [ $status -eq 0 ]; then
      printScreenWidth "$msg" FAILED
      echo "$modName already running"
      status=10
    else
      myEcho $msg
      IIM_PIDFILE=${calimbot_pidfile}
      export IIM_PIDFILE
      $execdaemon_cmd $java_cmd -Djava.awt.headless=true -cp $agents_classpath com.iplanet.im.server.JMSManager  -c ${config_file} &
      status=$?
      waitFor $calimbot_pidfile "$msg"
    fi
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file start $modName"
    status=$?
  else
    echo "$modName can be started by root or $IIMUSER only"
    status=3
  fi
  return $status
}


# Start services according to config file settings
start_iim() {
  status=128
  if [ "$service" = "" -a $watchdog_enabled -ne 0 ]; then
    start_watchdog
    status=$?
  else 
    if [ $server_enabled -ne 0 ]; then
      start_server
      status=$?
    fi

    if [ $multiplexor_enabled -ne 0 ]; then
      start_multiplexor
      status=$?
    fi

    if [ $agents_enabled -ne 0 ]; then
        start_calimbot
        status=$?
    fi
  fi
  return $status
}

# Stop the watchdog
stop_watchdog() {
  status=0
  verifyUid
  if [ $user_code -eq 1 ]; then
    stopProcess $wdpidfile Watchdog
    status=$?
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file stop watchdog"
    status=$?
  else
    echo "Watchdog can be stopped by root or $IIMUSER only"
    status=1 
  fi
  return $status
}

# Stop the server
stop_server() {
  status=0
  verifyUid
  if [ $user_code -eq 1 ]; then
    stopProcess $iimpidfile Server
    status=$?
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file stop server"
    status=$?
  else
    echo "Server can be stopped by root or $IIMUSER only"
    status=1 
  fi
  return $status

}

# Stop the multiplexor
stop_multiplexor() {
  status=0
  verifyUid
  if [ $user_code -eq 1 ]; then
    msg="Stopping Multiplexor"
    myEcho $msg
    status=`getStatus $muxpidfile`
    if [ $status -eq 0 ]; then
      $multiplexor_cmd -k -c $config_file
      printScreenWidth "" OK "$msg"
    else
      printScreenWidth "" FAILED "$msg"
      echo  "Multiplexor already stopped"
    fi
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file stop multiplexor"
  else
    echo "Multiplexor can be stopped by root or $IIMUSER only"
    status=1 
  fi
  return $status
}


# Stop the calendar im bot
stop_calimbot() {
  status=0
  modName=agent-calendar
  verifyUid
  if [ $user_code -eq 1 ]; then
    stopProcess $calimbot_pidfile $modName 
    status=$?
  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file stop $modName"
    status=$?
  else
    echo "$modName can be stopped by root or $IIMUSER only"
    status=1
  fi
  return $status
}


# Stop all running services according to config file settings
stop_iim() {
  status=0
  if [ "$service" != "legacy" ]; then
    running=`getStatus $wdpidfile`
    if [ $running -eq 0 -o $watchdog_enabled -ne 0 ]; then
      stop_watchdog
      status=$?
    fi
  fi

  running=`getStatus $iimpidfile`
  if [ $running -eq 0 -o $server_enabled -ne 0 ]; then
    stop_server
    status=$?
  fi

  running=`getStatus $muxpidfile`
  if [ $running -eq 0 -o $multiplexor_enabled -ne 0 ]; then
    stop_multiplexor
    status=$?
  fi

  running=`getStatus $calimbot_pidfile`
  if [ $running -eq 0 -o $agents_enabled -ne 0 ]; then
    stop_calimbot
    status=$?
  fi

  return  $status
}

# Restart the server and multiplexor
refresh() {
  stop_iim
  sleep $sleep_interval
  start_iim
  status=$?
  return $status
}

refresh_watchdog() {
  status=0
  stop_watchdog
  sleep $sleep_interval
  start_watchdog
  status=$?
  return $status
}

# Restart the server
refresh_server() {
  status=0
  stop_server
  sleep $sleep_interval
  start_server
  status=$?

  return $status
}

# Restart the multiplexor
refresh_multiplexor() {
  status=0
  stop_multiplexor
  sleep $sleep_interval
  start_multiplexor
  status=$?

  return $status
}

# Restart calendar im bot
refresh_calimbot() {
  status=0
  stop_calimbot
  sleep $sleep_interval
  start_calimbot
  status=$?
  
  return $status
}

# check whether enabled services are up
check() 
{
  ssl=0
  if [ $multiplexor_enabled -eq 0 ]; then
    service=`getValue iim_server.port`    
  else 
    service=`getValue iim_mux.listenport`
    usessl=`getValue iim_mux.usessl`
    if [ "$usessl" = "" ]; then
      usessl="off" 
    fi
    if [ "$usessl" = "on" -o "$usessl" = "true" -o "$usessl" = "yes" ]; then
      ssl=1
    fi
  fi

  if [ $ssl -eq 0 ]; then
    $java_cmd -Djava.awt.headless=true -cp $server_classpath com.iplanet.im.server.Monitor --nologin -t 0 -s $service
  else 
    $java_cmd -Djava.awt.headless=true -cp $server_classpath com.iplanet.im.server.Monitor --nologin -t 0 -s $service --ssl
  fi
  rc=$?

  if [ $rc -eq 0 ]; then
    echo "The IM service is UP"
  else 
    echo "The IM service is DOWN"
  fi
    
  return $rc
}

server_status() {
  status=`getStatus $iimpidfile`
  if [ $status -eq 0 ]; then
    printScreenWidth Server UP
  else
    printScreenWidth Server DOWN
  fi
  #echo $status
}

mux_status() {
  status=`getStatus $muxpidfile`
  if [ $status -eq 0 ]; then
    printScreenWidth Multiplexor UP
  else
    printScreenWidth Multiplexor DOWN
  fi
}

watchdog_status() {
  status=`getStatus $wdpidfile`
  if [ $status -eq 0 ]; then
    printScreenWidth Watchdog UP
  else
    printScreenWidth Watchdog DOWN
  fi
}

calimbot_status() {
  status=`getStatus $calimbot_pidfile`
  if [ $status -eq 0 ]; then
    printScreenWidth Agent:calendar UP
  else
    printScreenWidth Agent:calendar DOWN
  fi
}

system_status() {
loop=1
if [ "$1" != "" ]; then
  delay=$1
else 
  delay=-1
fi

while [ $loop -ne 0 ]; do
  if [ $delay -gt 0 ]; then
    $TPUT clear
  fi
  running=`getStatus $iimpidfile`
  if [ $server_enabled -ne 0 -o $running -eq 0 ]; then
    server_status 
  fi
  running=`getStatus $muxpidfile`
  if [ $multiplexor_enabled -ne 0 -o $running -eq 0 ]; then
    mux_status
  fi
  running=`getStatus $calimbot_pidfile`
  if [ $agents_enabled -ne 0 -o $running -eq 0 ]; then
    calimbot_status
  fi
  running=`getStatus $wdpidfile`
  if [ $watchdog_enabled -ne 0 -o $running -eq 0 ]; then
    watchdog_status
  fi
  if [ $delay -gt 0 ]; then
    sleep $delay
  else
    loop=0
  fi
done
}

print_version() {
  verifyUid
  if [ "$OS" = "Linux" ]; then
    rpm -q sun-im-server | cut -c15-
  else
    pkgparam SUNWiim VERSION
  fi
}


# do the right thing
#
case "${cmd}" in
  'start')
         if [ "$service" = "" ]; then
           start_iim
           status=`echo $?`
         elif [ "$service" = "server" ]; then
           start_server
           status=`echo $?`
         elif [ "$service" = "multiplexor" ]; then
           start_multiplexor
           status=`echo $?`
         elif [ "$service" = "watchdog" ]; then
           param=""
           if [ $# -gt 2 -a "$3" = "verbose" ]; then
             param="-v"
           fi
           start_watchdog $param
           status=`echo $?`
         elif [ "$service" = "calimbot" ]; then
           start_calimbot
           status=`echo $?`
         fi
         exit $status
         ;;
  'stop')
         if [ "$service" = "" ]; then
           stop_iim
           status=`echo $?`
         elif [ "$service" = "server" ]; then
           stop_server
           status=`echo $?`
         elif [ "$service" = "multiplexor" ]; then
           stop_multiplexor
           status=`echo $?`
         elif [ "$service" = "watchdog" ]; then
           stop_watchdog
           status=`echo $?`
         elif [ "$service" = "calimbot" ]; then
           stop_calimbot
           status=`echo $?`
         fi
         exit $status
         ;;
  'refresh')
	 if [ "$service" = "" ]; then
	   refresh
	   status=`echo $?`
         elif [ "$service" = "legacy" ]; then
           refresh
           status=`echo $?`
         elif [ "$service" = "server" ]; then
	   refresh_server
	   status=`echo $?`
         elif [ "$service" = "multiplexor" ]; then
	   refresh_multiplexor
	   status=`echo $?`
         elif [ "$service" = "watchdog" ]; then
           refresh_watchdog
           status=`echo $?`
         elif [ "$service" = "calimbot" ]; then
           refresh_calimbot
           status=`echo $?`
         fi
         exit $status
         ;;
  'version')
         print_version
         ;;
  'migrate')
        migrate_acl
        status=`echo $?`
        exit $status
        ;;
  'check')
        check
        status=`echo $?`
        exit $status
        ;;
  'status')
        status=0
        if [ "$service" = "" ]; then
          system_status $2
        elif [ "$service" = "server" ]; then
          server_status
        elif [ "$service" = "watchdog" ]; then
          watchdog_status
        elif [ "$service" = "multiplexor" ]; then
          mux_status
        elif [ "$service" = "calimbot" ]; then
          calimbot_status
        fi
        exit $status
        ;;
  *)
     usage
     ;;
esac

