#!/bin/bash

### BEGIN INIT INFO
# Provides:          guse
# Required-Start:    $remote_fs mysqld
# Required-Stop:     $remote_fs mysqld
# 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=ec2-user

# Source function library.
. /etc/rc.d/init.d/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
#
start()
{
        echo -n $"Starting gUSE: "
        check_jdk
        su - -s /bin/bash -c "$GUSE_USER_HOME"/start.sh "$GUSE_USER"
        action $"Starting gUSE " /bin/true
        return 0
}

#
# Function that stops the daemon/service
#
stop()
{
        echo -n $"Stopping gUSE: "
        su - -s /bin/bash -c "$GUSE_USER_HOME"/stop.sh "$GUSE_USER"
        action $"Stopping gUSE " /bin/true
        return 0
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart | reload | force-reload)
        stop
        start
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
        exit 3
        ;;
esac

exit 0
