#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          NetOffice
# Should-Start:      $network $named $time
# Should-Stop:       $network $named $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop the NetOffice daemon
# Description:       Controls the NetOffice daemon 
# Required-Start:
# Required-Stop:
### END INIT INFO
#
set -e
set -u
${DEBIAN_SCRIPT_DEBUG:+ set -v -x}

#test -x java -cp /usr/local/NetOffice/ NetOffice || exit 0

. /lib/lsb/init-functions

SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)

# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/netoffice -i"

# Safeguard (relative paths, core dumps..)
cd /
umask 077


## Checks if there is a server running and if so if it is accessible.
#
#
# Usage: boolean netoffice_status [check_alive|check_dead] [warn|nowarn]
netoffice_status () {
    ping_output=`telnet 127.0.0.1 65300 | grep Connected`; 

	ping_alive=`expr match "$ping_output" 'Connected'`

    if [ $ping_alive = 0 ]; then
  		return 1 # EXIT_FAILURE
    else
		return 0 # EXIT_SUCCESS
    fi
}

#
# main()
#

cd /usr/local/NetOffice

case "${1:-''}" in
  'start')
	# Start daemon
	log_daemon_msg "Starting NetOffice" "netoffice"
	if netoffice_status check_alive nowarn; then
	   echo "NetOffice is already running"
	   log_progress_msg "already running"
	   log_end_msg 0
	else
		echo "Starting NetOffice..."
	
	    case "${2:-''}" in
		'no_hacer_sudo')
		     cd /usr/local/NetOffice
		     java -cp /usr/local/NetOffice/ NetOffice > /dev/null 2>&1 &
		    ;;    
		*)
  	             su - www-data -c "/usr/local/NetOffice/start_netoffice"
		     ;;
	    esac
		
	    # 6s was reported in #352070 to be too few when using ndbcluster
	    for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14; do
                sleep 1
	        if netoffice_status check_alive nowarn ; then break; fi
		log_progress_msg "."
	    done
	    if netoffice_status check_alive warn; then
                log_end_msg 0
	    else
	        log_end_msg 1
		log_failure_msg "Please take a look at the syslog"
	    fi
	fi
	;;
  'stop')
	log_daemon_msg "Stopping NetOffice" "netoffice"
	if netoffice_status check_alive nowarn; then
   	  shutdown_out=`telnet 127.0.0.1 20000 < /usr/local/NetOffice/apagar.txt`
	    for i in 1 2 3 4 5 6 7 8 9 10; do
              sleep 1
              if netoffice_status check_dead nowarn; then server_down=1; break; fi
            done
        if ! netoffice_status check_dead warn; then
		  log_end_msg 1
		  log_failure_msg "Please stop NetOffice manually"
		  exit -1
		fi
	else
		echo "NetOffice already stopped!"
		log_end_msg 0
    fi
	;;

  'restart')
	set +e; $SELF stop; set -e
	$SELF start 
	;;

  'status')
	if netoffice_status check_alive nowarn; then
	  log_action_msg "NetOffice is running."
	else
	  log_action_msg "NetOffice is stopped."
	  exit 3
	fi
  	;;

  *)
	echo "Usage: $SELF start|stop|restart|status"
	exit 1
	;;
esac

