#!/usr/bin/ksh
# PROPRIETARY AND CONFIDENTIAL
# Copyright 1999-2001 Sun Microsystems, Inc. Some preexisting portions
# 
# Sun, Sun Microsystems, the Sun logo, Java, iPlanet, and all Sun, Java,
# and iPlanet-based trademarks and logos are trademarks or registered
# trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
#

# 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"
  echo "           multiplexor      - multiplexor only"
  echo "           server           - server only"
  echo ""
  exit 1
}

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

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

IIMUSER="inetuser"
USER=2
FROM_RPM=0

# get basic OS info, set OS-specific commands
OS="`uname -s`"
if [ "$OS" = "Linux" ]
then
  ID_CMD="/usr/bin/id -u"
  # Prevent .bashrc reading problems when calling su
  export BASH_ENV=""
  if [ ${RPM_INSTALL_PREFIX} ]; then
    FROM_RPM=1
  fi
else
  ID_CMD="/usr/xpg4/bin/id -u"
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
if test \! -r $config_file ; then
  # Be quite about the error if running from RPM
  if [ $FROM_RPM != 1 ]; then
    echo "Configuration file $config_file is missing, exiting"
  fi
  exit 1
fi
server_pid=""

java_cmd=`getValue iim.jvm.command`

server_enabled=1;
multiplexor_enabled=1;

if [ "$OS" = "Linux" ]
then
  # product class dir
  PCD=$installdir/classes
  # 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=$installdir/share/lib
else
  PCD=$installdir/classes
  PLD=$installdir/lib
  SCPuD=/usr/share/lib
  PPrLD=$installdir/classes
fi

#default classpath
server_classpath=$PCD/imxmpp.jar:$PCD/imserv.jar:$PCD/imservres.jar:$PCD/improvider.jar:$PCD/imservice.jar:$PPrLD/activation.jar:$PPrLD/mail.jar:$PPrLD/ens.jar:$PPrLD/jms.jar:$PPrLD/jaxp.jar:$PPrLD/xalan.jar:$PPrLD/crimson.jar:$PCD/icalendar.jar:$PCD/suncalendar.jar:$PCD/searchsdk.jar:$PPrLD/ldapjdk.jar:$PCD/imidutil.jar

#if( test `$ID_CMD` -eq 0 )
#then
#      chmod 755 /opt
#fi

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

# Go hunting for java_cmd if not found above and on Linux
if [[ -z $java_cmd ]]
then
 if [ "$OS" = "Linux" ]
 then
  jh=`printenv JAVA_HOME`
  if [ "$jh" != "" ]
  then
    java_cmd=$JAVA_HOME/bin/java
  else
    kitdir=`rpm -q --all|egrep 'jdk|jre|j2se|j2re|j2sdk'|head -1`
    if [ "$kitdir" != "" ]; then
      java_cmd=`rpm -q -l $kitdir|grep 'bin.java$'|head -1`
    fi
    if [ "$java_cmd" = "" ]
    then
      java_cmd=`which java`
      if [ "$java_cmd" = "" ]
      then
        echo "Sorry, no java command found"
        exit 1
      fi
    fi
  fi
 fi
fi

# detect presence of identity from packages
id_installed=0;
if [ "$OS" = "Linux" ]; then
  rpm -q sun-identity-sdk > /dev/null 2>&1
  if [[ $? = 0 ]] ; then
    id_installed=1
    id_package="sun-identity-sdk"
  else
    rpm -q sun-identity-services > /dev/null 2>&1
    if [[ $? = 0 ]] ; then
      id_installed=1
      id_package="sun-identity-services"
    else
      rpm -q SUNWamsdk > /dev/null 2>&1
      if [[ $? = 0 ]] ; then
	id_installed=1
	id_package="SUNWamsdk"
      else
	rpm -q SUNWamsvc > /dev/null 2>&1
	if [[ $? = 0 ]] ; then
	  id_installed=1
	  id_package="SUNWamsvc"
	fi
      fi
    fi
  fi
else
  pkginfo SUNWamsdk > /dev/null 2>&1
  if [[ $? = 0 ]] ; then
      id_installed=1
      id_package="SUNWamsdk"
  fi
  pkginfo SUNWamsvc > /dev/null 2>&1
  if [[ $? = 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.
  PROP_FILE="/etc/opt/SUNWam/config/AMConfig.properties"
  USESSO=`getValue iim_server.usesso`
  MODULE=`getValue iim.policy.modules`
  if [[ $USESSO = "0" && $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
      id_jre=`grep "jdk.path" $PROP_FILE|cut -f2 -d=`
    else
      id_basedir=`pkgparam -v $id_package |grep \^BASEDIR= | cut -f2 -d = |sed -e s/\'//g''` 
      id_jre=`pkgparam -v $id_package |grep \^JDK_BASE_DIR= | cut -f2 -d = |sed -e s/\'//g''`
    fi
  fi
fi

# 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
	exit 1
fi


# read some option from config file
if test -f $config_file; then
  IIMUSER=`getValue iim.user`
  
  # java command path
  if [[ -z $java_cmd ]]
  then
    java_cmd=`getValue iim.jvm.command`
    if [[ -z $java_cmd ]] 
    then
      java_cmd=$installdir/java/jre/bin/java
    fi
  fi
  
  # max mem size argument
  maxmemsize=`getValue iim.jvm.maxmemorysize`
  if [[ -z $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
  
  # identity sdk and jre locations
  val=`getValue iim.identity.basedir`
  if [[ ! -z $val ]] 
  then
    id_installed=1
    id_basedir=$val
  fi
  val=`getValue iim.identity.jre`
  if [[ ! -z $val ]] 
  then
    id_jre=$val
  fi

fi

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

# detect presence of iPS install
ips_installed=0;
pkginfo SUNWwtdt > /dev/null 2>&1
if [[ $? = 0 ]] ; then
  BASEDIR=`pkgparam -v SUNWwtdt |grep BASEDIR= | cut -f2 -d = |sed -e s/\'//g''`
  PRODUCT_DIR=`pkgparam -v SUNWwtdt |grep PRODUCT_DIR= | cut -f2 -d = |sed -e s/\'//g''`
  server_classpath=${server_classpath}:$BASEDIR/$PRODUCT_DIR/lib/ips_sdk.jar:$BASEDIR/$PRODUCT_DIR/lib/ips_services.jar:$BASEDIR/$PRODUCT_DIR/lib/sunjce_provider.jar:$BASEDIR/$PRODUCT_DIR/lib/jce1_2_1.jar:$BASEDIR/$PRODUCT_DIR/lib/xml.jar
  ips_installed=1;
fi

SEC_LIB_HOME=/

SEC_LIB_PATH=${SEC_LIB_HOME}/usr/lib/mps/secv1

if [ "$OS" = "Linux" ]; then
  JSS_JAR=${SEC_LIB_HOME}/usr/share/lib/mps/secv1/jss3.jar
  if ! [ -a $JSS_JAR ]; then
    JSS_JAR=${installdir}/classes/jss3.jar
  fi
else
  JSS_JAR=${SEC_LIB_HOME}/usr/share/lib/mps/secv1/jss3.jar
fi

if [[ $id_installed -eq 1 ]]; then
  AM_HOME=${id_basedir}/SUNWam
  JAXP_HOME=/usr/share/lib
  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
  AM_DIRS=${AM_HOME}/lib:${AM_HOME}/locale:/etc/opt/SUNWam/config
  JAXP_JARS=${JAXP_HOME}/jaxp-api.jar:${JAXP_HOME}/xalan.jar:${JAXP_HOME}/xercesImpl.jar:${JAXP_HOME}/sax.jar:${JAXP_HOME}/dom.jar

  AM_CLASSPATH=${AM_DIRS}:${SDK_JARS}:${JAXP_JARS} 

  server_classpath=${AM_CLASSPATH}:${id_jre}/lib/lib.zip:${server_classpath}
  if [ ! -z $id_jre ]
  then 
    java_cmd=${id_jre}/bin/java
  fi
fi
server_classpath=${JSS_JAR}:${server_classpath}

# set environment
ADDLIBPATH=${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
	    ;;
	[cC][hH][eE][cC][kK] )
	    cmd=check
	    ;;
	* ) printf "ERROR: Unknown command.\n\n"
	    usage
	    ;;
esac


# Set the service to act upon
#
if [[ $# -gt 1 ]] ; then
  case $2 in
          [iI][iI][mM] )
              ;;
          [sS][eE][rR][vV][eE][rR] )
              service=server
              ;;
          [mM][uU][lL][tT][iI][pP][lL][eE][xX][oO][rR] )
              service=multiplexor
              ;;
          [iI][iI][mM] )
              service=multiplexor
              ;;
          [iI][iI][mM]_[mM][uU][xX] )
              service=multiplexor
              ;;
          [iI][iI][mM]_[sS][eE][rR][vV][eE][rR] )
              service=server
              ;;
          * ) printf "ERROR: Unknown service.\n\n"
	      usage
	      ;;
  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_CMD`
  IIMUID=`$ID_CMD $IIMUSER`
  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
}
  
#
# Get pid from pidfile
# Assumes file contains pid as first line
getpid() {
  head -n 1 ${pidfile} 2>/dev/null
}

# Migrate acl file to LDAP
migrate_acl() {
  if [[ ! -d ${logdir} ]] ; then
    mkdir ${logdir}
  fi
  echo "Access control file migration starting"
  $java_cmd -cp $server_classpath -Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Dcom.iplanet.coreservices.configpath=${id_basedir}/SUNWam/config/ums -Djava.protocol.handler.pkgs=com.iplanet.services.comm 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 server
start_server() {
  verifyUid
  if [ $user_code -eq 1 ]; then
    if [[ -r ${pidfile} ]] ; then
      printf "server already running, try - imadmin refresh\n"
      return 1
    fi
 
    if [[ ! -d ${logdir} ]] ; then
      mkdir ${logdir}
    fi

    # add iim_server.usesso option if missing
    #if [[ $id_installed -eq 1 ]] ; then
    #  grep "iim_server.usesso" ${config_file} 1>/dev/null 2>&1
    #  if [[ $? -ne 0 ]] ; then
    #	echo "iim_server.usesso=1" >> ${config_file}
    #  fi  
    #fi

    IIM_PIDFILE=${pidfile}
    export IIM_PIDFILE
    printf "Starting server\n"
    if [[ $id_installed = 1 ]] ; then
        $execdaemon_cmd $java_cmd -server -Xmx${maxmemsize}m -cp $server_classpath -Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Dcom.iplanet.coreservices.configpath=${id_basedir}/SUNWam/config/ums -Djava.protocol.handler.pkgs=com.iplanet.services.comm com.iplanet.im.server.NMS -c $config_file -w 15 &
    else
        $execdaemon_cmd $java_cmd -server -Xmx${maxmemsize}m -cp $server_classpath com.iplanet.im.server.NMS -c $config_file -w 15 &
    fi

  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file start server"
  else
    echo "Server can be started by root or $IIMUSER only"
    return 1 
  fi
  return 0
}

# Start the multiplexor
start_multiplexor() {
  verifyUid
  if [ "$OS" = "Linux" ]; then
    ulimit -n 4096
  fi
  if [ $user_code -eq 1 ]; then
    printf "Starting multiplexor\n"
    $multiplexor_cmd -c $config_file&
  elif [ $user_code -eq 0 ]; then
    printf "Starting multiplexor\n"
    su $IIMUSER -c "$multiplexor_cmd -c $config_file&"
  else
    echo "Multiplexor can be started by root or $IIMUSER only"
    return 1 
  fi
  return 0
}

# Start server and multiplexor
start_iim() {
  if [ $server_enabled -ne 0 ]; 
  then
    start_server
    if [[ $? -ne 0 ]] ; then
      printf "server not started.\n"
      return 1
    fi
  fi

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

  return 0
}

# Stop the server
stop_server() {
  verifyUid
  if [ $user_code -eq 1 ]; then
    printf "Stopping server\n"

    if [[ ! -r ${pidfile} ]] ; then
  	printf "server not running.\n"
  	return 1
    fi

    server_pid=`getpid $pidfile`
    rm -f $pidfile
    /bin/ps -p ${server_pid} > /dev/null 2>&1
    if [[ $? -ne 0 ]] ; then
  	printf "server not running.\n"
        return 1
    fi

    kill $server_pid
    /bin/ps -p ${server_pid} > /dev/null 2>&1
    if [[ $? = 0 ]] ; then
      echo Retrying kill server
      kill $server_pid
      sleep 1
      /bin/ps -p ${server_pid} > /dev/null 2>&1
      if [[ $? = 0 ]] ; then
        echo Forcibly killing server
        kill -9 $server_pid
      fi
    fi

  elif [ $user_code -eq 0 ]; then
    su $IIMUSER -c "$admindir/imadmin -c $config_file stop server"
  else
    echo "Server can be stopped by root or $IIMUSER only"
    return 1 
  fi
  return 0

}

# Stop the multiplexor
stop_multiplexor() {
  verifyUid
  if [ $user_code -eq 1 ]; then
    printf "Stopping multiplexor\n"
    $multiplexor_cmd -k -c $config_file
  elif [ $user_code -eq 0 ]; then
    printf "Stopping multiplexor\n"
    su $IIMUSER -c "$multiplexor_cmd -k -c $config_file"
  else
    echo "Multiplexor can be stopped by root or $IIMUSER only"
    return 1 
  fi
  return 0
}

# Stop the server and multiplexor
stop_iim() {
  if [ $server_enabled -ne 0 ]; 
  then
    stop_server
    status=`echo $?`
  fi

  if [ $multiplexor_enabled -ne 0 ]; 
  then
    stop_multiplexor
  fi

  return  $status
}

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

# Restart the server
refresh_server() {
  stop_server
  sleep $sleep_interval
  start_server
  return 0
}

# Restart the multiplexor
refresh_multiplexor() {
  stop_multiplexor
  sleep $sleep_interval
  start_multiplexor
  return 0
}

# 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 [ -z $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 -cp $server_classpath com.iplanet.im.server.Monitor --nologin -t 0 -s $service
  else 
    $java_cmd -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
}


# do the right thing.
#
case "${cmd}" in
  'start')
         if [ -z $service ]
         then
	   start_iim
	   status=`echo $?`
         elif [ $service = "server" ]
         then
	   start_server
	   status=`echo $?`
         elif [ $service = "multiplexor" ]
         then
	   start_multiplexor
	   status=`echo $?`
         fi
         exit $status
         ;;
  'stop')
         if [ -z $service ]
         then
	   stop_iim
	   status=`echo $?`
         elif [ $service = "server" ]
         then
	   stop_server
	   status=`echo $?`
         elif [ $service = "multiplexor" ]
         then
	   stop_multiplexor
	   status=`echo $?`
         fi
         exit $status
         ;;
  'refresh')
	 if [ -z $service ]
	 then
	   refresh
	   status=`echo $?`
         elif [ $service = "server" ]
         then
	   refresh_server
	   status=`echo $?`
         elif [ $service = "multiplexor" ]
         then
	   refresh_multiplexor
	   status=`echo $?`
         fi
         exit $status
         ;;
  'version')
         cat ${installdir}/iim.version
         ;;
  'migrate')
        migrate_acl
        status=`echo $?`
        exit $status
        ;;
  'check')
        check
        status=`echo $?`
        exit $status
        ;;
  *)
     usage
     exit 2
     ;;
esac


