#!/bin/bash
#
# Init file for perfSONAR MA data conversion tool
#
# chkconfig: 2345 99 20
# description: perfSONAR MA data conversion tool
#

PREFIX=/opt/perfsonar_ps/toolkit
BINDIR=${PREFIX}/scripts
RUNDIR=/var/run
LOGFILE=/var/log/perfsonar/psb_to_esmond.log
PIDFILE=${RUNDIR}/psb_to_esmond.pid
STATEFILE=/var/lib/perfsonar/db_backups/psb_to_esmond.state
OWMESH=/opt/perfsonar_ps/perfsonarbuoy_ma/etc
USER=perfsonar
GROUP=perfsonar

#Get the MA key
export ESMOND_ROOT=/opt/esmond
export ESMOND_CONF=$ESMOND_ROOT/esmond.conf
export DJANGO_SETTINGS_MODULE=esmond.settings
cd /opt/esmond
source /opt/rh/python27/enable
. bin/activate
MA_KEY=`python esmond/manage.py add_ps_metadata_post_user perfsonar | grep "Key:" | cut -f2 -d " "`

PERFSONAR="${BINDIR}/psb_to_esmond.pl -d --pidfile=${PIDFILE} --logfile=${LOGFILE} --user=${USER} --group=${GROUP} --statefile ${STATEFILE} --owmesh-dir ${OWMESH} --mapassword ${MA_KEY}"

ERROR=0
ARGV="$@"
if [ "x$ARGV" = "x" ] ; then 
    ARGS="help"
fi

for ARG in $@ $ARGS
do
    # check for pidfile
    if [ -f $PIDFILE ] ; then
        PID=`cat $PIDFILE`
        if [ "x$PID" != "x" ] && kill -0 $PID 2>/dev/null ; then
            STATUS="perfSONAR MA Data Conversion (pid $PID) running"
            RUNNING=1
        else
            STATUS="perfSONAR MA Data Conversion (pid $PID?) not running"
            RUNNING=0
        fi
    else
        STATUS="perfSONAR MA Data Conversion (no pid file) not running"
        RUNNING=0
    fi 

    case $ARG in
    start)
	echo $PERFSONAR

	if $PERFSONAR ; then
	    echo "$0 $ARG: perfSONAR MA Data Conversion started"
	else
	    echo "$0 $ARG: perfSONAR MA Data Conversion could not be started"
	    ERROR=3
	fi
	;;
    stop)
	if [ $RUNNING -eq 0 ]; then
	    echo "$0 $ARG: $STATUS"
	    continue
	fi
	if kill $PID ; then
	    echo "$0 $ARG: perfSONAR MA Data Conversion stopped $PID"
	else
	    echo "$0 $ARG: perfSONAR MA Data Conversion could not be stopped"
	    ERROR=4
	fi
	;;
    restart)
    	$0 stop; echo "waiting..."; sleep 10; $0 start;
	;;
    *)
	echo "usage: $0 (start|stop|restart|help)"
	cat <<EOF

start      - start perfSONAR MA Data Conversion
stop       - stop perfSONAR MA Data Conversion
restart    - restart perfSONAR MA Data Conversion Service if running by sending a SIGHUP or start if 
             not running
help       - this screen

EOF
	ERROR=2
    ;;

    esac

done

exit $ERROR

