#!/bin/bash

### BEGIN INIT INFO
# Provides: NetOffice
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: NetOffice initscript
# Description: NetOffice init script, to be placed in /etc/init.d.
#
### END INIT INFO

## Fill in name of program here.
PROG="NetOffice"
PROG_PATH="/usr/bin"
PROG_ARGS=""
ARG1=$1
ARG2=$2

#. /lib/lsb/init-functions

echo ""
echo "Script de inicio para $PROG"

# Esta función nos devolverá el estado del NetOffice
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
}

# Hacemos un cd al directorio del programa
cd /usr/local/NetOffice

# Función de inicio
start() {
    echo "Arrancando $PROG..." " $PROG "
    if netoffice_status check_alive nowarn; then
        echo "$PROG ya se encuentra en ejecución!"
        exit 0
    else
	echo "$PROG no está iniciado, voy a arrancarlo"
	if test "$ARG2" = "no_hacer_sudo"; then
	     #echo "Ejecutaré $PROG sin hacer sudo"
             cd /usr/local/NetOffice
             java -cp /usr/local/NetOffice/ NetOffice > /dev/null 2>&1 &
        fi
        su -s /bin/bash www-data -c "/usr/local/NetOffice/start_netoffice" > /dev/null 2>&1 &
    fi
}

# Función para detener el servicio
stop() {
    echo "Deteniendo $PROG..." " $PROG "
    if netoffice_status check_alive nowarn; then
        ## Program is running, so stop it
	telnet 127.0.0.1 20000 < /usr/local/NetOffice/apagar.txt
        echo "$PROG detenido"
    else
        ## Program is not running, exit with error.
        echo "$PROG ya estaba detenido!" 1>&2
        exit 0
    fi
}

## Check to see if we are running as root first.
if [ "$(id -u)" != "0" ]; then
    echo "IMPORTANTE: Este script debería ejecutarse como root" 1>&2
    #exit 1
fi

# Función para comprobar el estado del servicio
status() {
	if netoffice_status check_alive nowarn; then
        	echo "$PROG se encuentra en ejecución."
        else
        	echo "$PROG se encuentra detenido."
        	exit 3
        fi
}

# Definimos los parámetros que puede pasar el usuario
# y ejecutamos las funciones correspondientes
case "$1" in
    start)
        start
        exit 0
    ;;
    stop)
        stop
        exit 0
    ;;
    status)
	status
	exit 0
    ;;
    reload|restart|force-reload)
        stop
        start
        exit 0
    ;;
    **)
        echo "Usage: $0 {start|stop|status|reload}" 1>&2
        exit 1
    ;;
esac
