#!/bin/sh 
#
# todo: 
#  1) fall back to kill -9 on stop if server doesn't stop
#

usage () {
  echo 'Usage: xmppd {start|stop|version}'
  echo ""
  echo ""
  exit 1
}

mydir=`dirname $0`
cd $mydir

install_dir=..

if [ $# -lt 1 ]; then
  usage
  exit 1
fi

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
    ;;
  * ) printf "ERROR: Unknown command.\n\n"
    usage
    ;;
esac

config_file=$install_dir/config/xmppd.conf

# 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
}

java_cmd=`getValue iim.jvm.command`

LD_LIBRARY_PATH=/opt/sun/private/lib

# Change these parameters to the standard location
SHARE_LIB_DIR=$installdir/lib
XMPP_LIB_DIR=$installdir/lib
JSS_LIB_DIR=$installdir/lib

# Solaris standard location
#SHARE_LIB_DIR=/usr/share/lib
#XMPP_LIB_DIR=/usr/share/lib/xmpp
#JSS_LIB_DIR=/usr/share/lib/mps/secv1

# Linux standard location
#SHARE_LIB_DIR=/opt/sun/share/lib
#XMPP_LIB_DIR=/opt/sun/private/share/lib
#JSS_LIB_DIR=/usr/share/lib/mps/secv1


case "${cmd}" in

  'start')
    if test -f $install_dir/log/xmppd.pid; then
      echo Server already running, exiting
      exit 1
    fi

    mkdir -p $install_dir/log

    $java_cmd -server -Xmx256m -cp $SHARE_LIB_DIR/jso.jar:$SHARE_LIB_DIR/xp.jar:$SHARE_LIB_DIR/log4j.jar:$SHARE_LIB_DIR/jaxen-core.jar:$SHARE_LIB_DIR/saxpath.jar:$SHARE_LIB_DIR/imservice.jar:$XMPP_LIB_DIR/xmppd.jar:$XMPP_LIB_DIR/improvider.jar:$JSS_LIB_DIR/jss4.jar com.iplanet.im.server.NMS -c $config_file -w 15 &

    echo $! > $install_dir/log/xmppd.pid
    ;;

  'stop')
    if test -f $install_dir/log/xmppd.pid; then
      kill `cat $install_dir/log/xmppd.pid`
      rm -f $install_dir/log/xmppd.pid
    else
      echo "No server running."
    fi
    ;;

  'version')
    echo "7.0"
    ;;

  *)
    usage
    exit 2
    ;;
esac

