#!/bin/bash
#
# chkconfig: 345 99 05 
# description: Java deamon script
#
# A non-SUSE Linux start/stop script for Java daemons.
#
# Derived from -
# Home page: http://www.source-code.biz
# License:   GNU/LGPL (http://www.gnu.org/licenses/lgpl.html)
# Copyright 2006 Christian d'Heureuse, Inventec Informatik AG, Switzerland.
#
# History:
# 2010-09-21 Josh Davis: Changed 'sudo' to 'su', fix some typos, removed unused variables
# 2009-03-04 Josh Davis: Ubuntu/Redhat version.
# 2006-06-27 Christian d'Heureuse: Script created.
# 2006-07-02 chdh: Minor improvements.
# 2006-07-10 chdh: Changes for SUSE 10.0.
#
# OS specific support.  $var _must_ be set to either true or false.
#
cygwin=false;
darwin=false;
case "`uname`" in
  CYGWIN*) cygwin=true ;;
  Darwin*) darwin=true
           if [ -z "$JAVA_HOME" ] ; then
             JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre 
           fi
           ;;
esac

#
# Get the FTPD_HOME variable
#
FTPD_HOME=/usr/bin/wifi_vc/ftpserver;


#
# Get the Java command
#
if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME "
    fi
  else
    JAVACMD=`which java 2> /dev/null `
    if [ -z "$JAVACMD" ] ; then
        JAVACMD=java
    fi
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi


#
# Get the path separator
#
if [ "$cygwin" = "true" ] ; then
  S=';'
else
  S=':'
fi


#
# Build classpath
#
if [ "$cygwin" = "true" ] ; then
    FTPD_CLASSPATH=$CLASSPATH$S`cygpath -w $FTPD_HOME/common/classes`
else
    FTPD_CLASSPATH=$CLASSPATH$S$FTPD_HOME/common/classes
fi

for i in $FTPD_HOME/common/lib/*.jar; do
  if [ "$cygwin" = "true" ] ; then
    LIB=`cygpath -w $i`
  else
    LIB=$i
  fi

  FTPD_CLASSPATH=$FTPD_CLASSPATH$S$LIB
done


#
# Execute command
#
#CURR_DIR=`pwd`
#echo $FTPD_HOME
#echo "---------------------"
#cd $FTPD_HOME
MAIN_CLASS=org.apache.ftpserver.main.CommandLine
#echo "ftpd_classpath:" $FTPD_CLASSPATH
#"$JAVACMD" -classpath "$FTPD_CLASSPATH" $MAIN_CLASS $@ &
#RESULT=$?
#cd $CURR_DIR
#exit $RESULT



# Set this to your Java installation
# for example:
# JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre 
JAVA_HOME=

serviceNameLo="virtualcoordinatorFTP2"        # service name with the first letter in lowercase
serviceName="virtualcoordinatorFTP2"          # service name
serviceUser="root"                     # OS user name for the service
serviceGroup="root"                    # OS group name for the service
applDir="/usr/bin/wifi_vc/ftpserver"   # home directory of the service application
serviceUserHome="/$serviceUser"      # home directory of the service user
serviceLogFile="/usr/bin/wifi_vc/logs/$serviceNameLo.log" # log file for StdOut/StdErr
maxShutdownTime=15   # maximum number of seconds to wait for the daemon to terminate normally
pidFile="/usr/bin/wifi_vc/$serviceNameLo.pid"  # name of PID file (PID = process ID number)
javaCommand="java"                    # name of the Java launcher without the path
javaExe="/usr/bin/$javaCommand" # file name of the Java application launcher executable
javaArgs="-classpath $FTPD_CLASSPATH $MAIN_CLASS res/conf/ftpd-typical.xml" # arguments for Java launcher
javaCommandLine="$javaExe $javaArgs"      # command line to start the Java service application
javaCommandLineKeyword="ftpd"    # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others

# Makes the file $1 writable by the group $serviceGroup.
function makeFileWritable {
   local filename="$1"
   touch $filename || return 1
   chgrp $serviceGroup $filename || return 1
   chmod g+w $filename || return 1
   return 0; }

# Returns 0 if the process with PID $1 is running.
function checkProcessIsRunning {
	#echo "Inside checkProcessIsRunning pid=" $1;
	
   local pid="$1"
   if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi
   if [ ! -e /proc/$pid ]; then return 1; fi
   return 0; }

# Returns 0 if the process with PID $1 is our Java service process.
function checkProcessIsOurService {
   local pid="$1"
   if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi
   grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline
   if [ $? -ne 0 ]; then return 1; fi
   return 0; }

# Returns 0 when the service is running and sets the variable $pid to the PID.
function getServicePID {
   if [ ! -f $pidFile ]; then return 1; fi
   pid="$(<$pidFile)"
   #echo "in getservicepid" $pid;	

   checkProcessIsRunning $pid || return 1
   #echo $pid "process is running, checking if our service";
   checkProcessIsOurService $pid || return 1
   return 0; }

function startServiceProcess {
   cd $applDir || return 1
   #echo "ajay...";
   #pwd
   rm -f $pidFile
   makeFileWritable $pidFile || return 1
   makeFileWritable $serviceLogFile || return 1
   cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile"
   #echo ".......Ajay....cmd=$cmd";
   su -m $serviceUser -s $SHELL -c "$cmd" || return 1
   sleep 0.1
   pid="$(<$pidFile)"
   #echo $pid;
   if checkProcessIsRunning $pid; then :; else
      echo -ne "\n$serviceName start failed, see logfile."
      return 1
   fi
   return 0; }

function stopServiceProcess {
   kill $pid || return 1
   for ((i=0; i<maxShutdownTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..."
   kill -s KILL $pid || return 1
   local killWaitTime=15
   for ((i=0; i<killWaitTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
   return 1; }

function startService {
   getServicePID
   if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi
   echo -n "Starting $serviceName   "
   startServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "started PID=$pid"
   RETVAL=0
   return 0; }

function stopService {
   getServicePID
   if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi
   echo -n "Stopping $serviceName   "
   stopServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "stopped PID=$pid"
   RETVAL=0
   return 0; }

function checkServiceStatus {
   echo -n "Checking for $serviceName:   "
   if getServicePID; then
	echo "running PID=$pid"
	RETVAL=0
   else
	echo "stopped"
	RETVAL=3
   fi
   return 0; }

function main {
   RETVAL=0
   case "$1" in
      start)                                               # starts the Java program as a Linux service
         startService
         ;;
      stop)                                                # stops the Java program service
         stopService
         ;;
      restart)                                             # stops and restarts the service
         stopService && startService
         ;;
      status)                                              # displays the service status
         checkServiceStatus
         ;;
      *)
         echo "Usage: $0 {start|stop|restart|status}"
         exit 1
         ;;
      esac
   exit $RETVAL
}

main $1

