#!/bin/sh

MNAME=`uname -n`
OKCHAT_HOME="/public/chat/server"

LOG_DIR=$OKCHAT_HOME
LOG_FILE_LINK=$LOG_DIR/current.log
JAVA_HOME="/usr/lib/jdk1.2.2/bin"
PID_FILE=$OKCHAT_HOME/okchat.pid
LOCK_FILE=$OKCHAT_HOME/OKCHAT.LCK
ALIVE_FILE=$OKCHAT_HOME/server.alive

RESTART_DELAY=30
CHECK_DELAY=10

case "$1" in
'stop')
        echo "Explicitly stop called";

 rm -f $PID_FILE 2>/dev/null;
 
 for PIDS in `ps -jef | grep okchat | grep /usr/lib/jdk1.2.2 | awk '{ print $2 }' `;
 do
  echo "Killing PID $PIDS"
  kill -9 $PIDS;
 done 

 echo "done"
        ;;

'status')
 ERROR=0;

 echo "checking for running startokchat.sh";
 if (test -z "`ps -jef | grep 'startokchat.sh start CLEAN' `");
 then
  echo "Restarting startokchat.sh in background";
  nohup $OKCHAT_HOME/startokchat.sh start CLEAN &
  exit 1;
 fi

 echo "check for running okchat"
 if (test -z "`ps -jef | grep root | grep java `");
 then
  echo "No JVMs found";
  ERROR=1;
 fi

 echo "check for alive file"
 if (test ! -e $ALIVE_FILE);
 then
  echo "No $ALIVE_FILE found";
  ERROR=1;
 else
  echo "Dont start $0 status the next 20 seconds - thanks";
  rm -rf $ALIVE_FILE;
 fi

 if ($ERROR -eq 0);
 then
  echo "OkChat OK";
  exit 0;
 else
  echo "Error occured - killing all JVMs";
  $0 stop

  exit 1;
 fi

 ;;

'start')
 
 # test if exists PID
 if (test -f "$PID_FILE" )
 then
  if [ $2 = "CLEAN" ];
  then
   rm -rf $PID_FILE;
  else
   echo "Found PID file $PID_FILE - check okchat"
   exit 1
  fi
 fi


 while (true);
 do
  echo 
  echo "==============================="
  echo "Restarted at: `date`"
  echo
  
  LOG_FILE="start_log.`date +"%H%M_%d%m"`"

  # delay startup
  while (test -e "$LOCK_FILE");
  do
   #echo "Lockfile $LOCK_FILE exists - suspending for $CHECK_DELAY seconds";
   sleep $CHECK_DELAY;
  done

  # compressing logs
  echo "Removing logfile link $LOG_FILE_LINK...";
  rm $LOG_FILE_LINK 2>&1 >/dev/null ;
  echo "done";

  echo "Starting jvm..."
  $JAVA_HOME/java -classpath .:$OKCHAT_HOME  ChatServer debug 2>&1 >$LOG_FILE &
 
  echo "setting up link $LOG_FILE_LINK --> $LOG_FILE"
  ln -s $LOG_FILE $LOG_FILE_LINK

  echo "Waiting for PID $!";
  echo $! > $PID_FILE ;
  wait $! ;

  rm -rf $PID_FILE

  echo "sleeping $RESTART_DELAY seconds before restart"
  sleep $RESTART_DELAY
 done

 echo "Ooops - shouldn't happen"

 $0 stop
 ;;

'restart')
 $0 stop
 ;;

'log')
       tail -f $LOG_FILE_LINK
        ;;

'startlog')
       tail -f $OKCHAT_HOME/nohup.out
        ;;

*)
 echo "usage: $0 {stop|start|restart|log}"
 ;;

esac
exit 0