#!/bin/sh


JWS_HOME=$0
[ "x$(readlink $0)" != "x" ] && JWS_HOME=$(readlink $0)
JWS_HOME=$(cd $(dirname $JWS_HOME);pwd)

[ $(ulimit -n) -lt 50000 ] && ulimit -SHn 50000 >/dev/null 2>&1

export LANG="zh_CN.UTF-8"
export LD_LIBRARY_PATH=${JWS_HOME}/runtime/lib:$LD_LIBRARY_PATH
export PATH=${JWS_HOME}/runtime/bin:$PATH
# export MONO_MANAGED_WATCHER="disable"
# export MONO_EXTERNAL_ENCODINGS="gbk:gb18030:gb2312"
# export MONO_STRICT_MS_COMPLIANT="yes"
# export MONO_GC_PARAMS="max-heap-size=3g"
# export MONO_DISABLE_AIO=1
export MONO_ASPNET_WEBCONFIG_CACHESIZE=8192
export MONO_THREADS_PER_CPU=2000

get_jws_pid()
{
    pid=`cat /var/run/jexus/jws.pid 2>/dev/null`
    [ "$pid" = "" ] && pid=0
    echo $pid
}

get_status()
{
      pid=`cat /var/run/jexus/jws.pid 2>/dev/null`
      [ "$pid" = "" ] && return 0

      jws_status=`ps -e | grep $pid | wc -l`
      [ $jws_status -ge 1 ] && return 1
      return 0
}

wait_new()
{
    for i in $(seq 1 30) 
    do
	echo -n '.'
        sleep 1
        p=`cat /var/run/jexus/jws.pid 2>/dev/null`
        [ "$p" = "" ] && continue
        [ "$1" != "$p" ] && return
    done
}


StopJws(){
    ${JWS_HOME}/jwss -stop </dev/null >/dev/null 2>&1
}


case "$1" in

  start)
      [ "x$2" != "x" ] && {
          [ "$2" = "-D" ] && {
              trap "StopJws" SIGTERM
              ${JWS_HOME}/jwss
              trap "" SIGTERM
              exit 0
          }

          ${JWS_HOME}/jwss -reapp "$2"
          exit 0
      }

      echo -n "Starting "
      oldpid=$(get_jws_pid)
      ${JWS_HOME}/jwss </dev/null >/dev/null 2>&1 &
      wait_new $oldpid
      get_status
      [ $? = 1 ] && echo " OK." && exit 0
      echo " Failure." && exit 1
      ;;

  stop)
      [ "x$2" != "x" ] && {
        ${JWS_HOME}/jwss -stop "$2"
        exit 0
      }
      ${JWS_HOME}/jwss -stop
      exit 0
      ;;

  restart)
      if [ "x$2" != "x" ]; then
          if [ "$2" = "-D" ]; then
              trap "StopJws" SIGTERM
              ${JWS_HOME}/jwss
              exit 0
          fi
          ${JWS_HOME}/jwss -reapp "$2"
          exit 0
      fi

      echo -n "Restarting "
      oldpid=$(get_jws_pid)
      ${JWS_HOME}/jwss -stop >/dev/null 2>&1
      ${JWS_HOME}/jwss </dev/null >/dev/null 2>&1 &
      wait_new $oldpid
      get_status
      [ $? -eq 1 ] && echo " OK." && exit 0
      echo " Failure." && exit 0
      ;;

  init)
      chmod +x ${JWS_HOME}/jwss
      chmod +x ${JWS_HOME}/runtime/bin/*
      [ -f /usr/bin/jws ] && rm -f /usr/bin/jws
      ln -s ${JWS_HOME}/jws /usr/bin/jws
      ;;

  status)
      get_status
      [ $? -eq 1 ] && {
          echo "Jexus is running."
          exit 0
      }
      echo "Jexus not running."
      exit 0
      ;;

  getid)
      ${JWS_HOME}/jwss --getid
      ;;

  -V|--version)
      ${JWS_HOME}/jwss -V
      ;;

  *)
      echo "Usage: jws {start|stop|restart|getid|init|status|-V|--version}"
      exit 1
      ;;
esac


exit 0
