#!/bin/bash
VERSION=1.0
#
# dplus D-STAR utility startup script
#
# Description: starts, stops, restarts dplus daemon
#
# description: Manages AA4RC's dplus application 
#

if [ $UID != 0 ]; then
	echo
	     echo "ERROR:  This script must be run as the root user!"
	     echo "        Please use 'su' or log in as root and try again."
	     echo
	     exit 1
 fi

TOOLS="/dstar/tools"
DPLUS=$TOOLS/dplus
STARTUP_MESSAGE="/dstar/dv/system-ready.dv"
DSTARGW=/opt/products/dstar/dstar_gw
DSIPSVD=$DSTARGW/dsipsvd/dsipsvd.conf
DSGWD=$DSTARGW/dsgwd/dsgwd.conf
LOG=/var/log/dplus.log
#
export LD_LIBRARY_PATH=/opt/products/dstar/pgsql/lib
#
DPLUS_VER=`$DPLUS -v 2>/dev/null`

#
# Make sure the dstar gateway configuration files exist
#
if [ ! -r $DSIPSVD ]; then
    echo "$DSIPSVD doesn't exist!"
    failure
    echo
    exit
fi

if [ ! -r $DSGWD ]; then
    echo "$DSGWD doesn't exist!"
    failure
    echo
    exit
fi
#
# Read gateway call and DNS path from config file.
#
GW_CALL=`egrep -e '^ZR_CALLSIGN' $DSIPSVD | sed -e 's/ //g' | awk -F"=" '{print $2}' |sed -e 's/\r//'`

#
# Display version
# 

version() {
	   echo "$VERSION"
	   exit
}

start() {

# Start daemons.

#
# start dplus, if it exists, otherwise complain, then quit.
#
    if [ ! -x $DPLUS ]; then
	echo -n "$DPLUS: not installed!"
	echo
	exit 1
    fi

    if [ -n "`/sbin/pidof $DPLUS`" ]; then
	echo -n "$DPLUS: already running!"
	echo
	exit 1
    else
	echo -n "Starting $DPLUS "
	/usr/bin/nohup $DPLUS -c $GW_CALL > $LOG 2>&1 &
	sleep 2
	if [ -n "`/sbin/pidof dplus`" ]; then
	    /bin/echo
	    if [ -f $STARTUP_MESSAGE ]; then
		for module in {a,b,c}
		  do
		  cp $STARTUP_MESSAGE /dstar/tmp/play-$module.dvtool
		  sleep 2
		done
	    fi
	    return 0
	else 
	    echo
	    return 1
	fi
    fi
}

stop() {
    
# Stop dplus

    echo -n "Stopping: dplus "
    PID1=`/sbin/pidof dplus`
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
	echo -e "\n\tERROR:  $DPLUS is NOT running!"
	return 1
    else
	/bin/kill $PID1
	/bin/echo
	return 0
    fi
}

restart() {

    stop
    sleep 2
    start
    return $?
}	

update () {
    /dstar/tools/dplus-check.sh 2>/dev/null
    exit
}

status() {

    PID=`/sbin/pidof dplus`
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
	echo "dplus is NOT running!"
    else 
	echo "dplus is running, PID = $PID, version = $DPLUS_VER"
    fi
}
	
# See how we were called.
case "$1" in
    start)
	start
	exit $?
	;;
    stop)
	stop
	exit $?
	;;
    restart)
	restart
	exit $?
	;;
    version)
	version
	;;
    update)
	update
	;;
    status)
	status
	;;
    *)
	echo -e $"\nUsage: \n\t$0 {option}"
	echo -e "\n\tOptions:\n"
	echo -e "\trestart       - restarts dplus"
	echo -e "\tstart         - starts dplus"
	echo -e "\tstatus        - display status"
	echo -e "\tstop          - stops dplus"
	echo -e "\tversion       - display script version and exit"
	echo -e "\n"
	exit 1
esac

exit $RETVAL
