#!/bin/bash

### BEGIN INIT INFO
# Provides:          guse
# Required-Start:    $remote_fs mysql
# Required-Stop:     $remote_fs mysql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: gUSE init script
# Description:       This file is used as the init script of WS-PGRADE/gUSE
### END INIT INFO

# Author: Zoltan Farkas <zoltan.farkas@sztaki.mta.hu>

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="gUSE init script"
NAME=guse
SCRIPTNAME=/etc/init.d/$NAME

# Set here the name of the user running the gUSE service
#GUSE_USER=guse

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

# Set gUSE user's home directory
GUSE_USER_HOME=`eval echo ~"$GUSE_USER"`

# Some sanity checks
[ -z "$GUSE_USER" ] && log_failure_msg "failesd to manage gUSE services, as variable \"GUSE_USER\" is not set in $SCRIPTNAME" && exit -1
[ ! -f "$GUSE_USER_HOME"/.guserc ] && log_failure_msg "falied to manage gUSE service, as no .guserc exists in specified user's home" && exit -1

check_jdk()
{
        update-alternatives --display java 2> /dev/null | grep -q "link currently points.*sun"
        [ $? != 0 ] && log_warning_msg "The 'java' alternative is not set to SUN (Oracle) JDK's 'java', you may experience problems with DCI Bridge plugins"
}

#
# Function that starts the daemon/service
#
do_start()
{
        log_begin_msg "Starting gUSE..."
        check_jdk
        su - -s /bin/bash -c "$GUSE_USER_HOME"/start.sh "$GUSE_USER"
        log_end_msg 0
        return 0
}

#
# Function that stops the daemon/service
#
do_stop()
{
        log_begin_msg "Stopping gUSE..."
        su - -s /bin/bash -c "$GUSE_USER_HOME"/stop.sh "$GUSE_USER"
        log_end_msg 0
        return 0
}

case "$1" in
  start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  stop)
        [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop}" >&2
        exit 3
        ;;
esac

:
