#!/bin/bash
#
# ridelogic_daemon_manager
#
# Copyright (c) 2019 Clementine Computing LLC.
# 
# This file is part of PopuFare.
# 
# PopuFare is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# PopuFare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
#


. /etc/rc.d/init.d/functions

if [ -f /etc/ridelogic/daemon.conf ]
then
        . /etc/ridelogic/daemon.conf
else
        echo "Missing config file /etc/ridelogic/daemon.conf, exiting"
        exit 1
fi

daemon=( ridelogic_avlsd ridelogic_buspassd ridelogic_billingd ridelogic_hellod ridelogic_versiond )

prog=''
for d in ${daemon[@]} 
do
        if [ "$1" == $d ]
        then
                prog=$d
                break
        fi
done

if [ -z "$1" ] || [ -z "$prog" ]
then
  echo "Usage: $0 daemon (start|stop|restart|condrestart)"
  exit 1
fi

path="$RIDELOGIC_DAEMON_DIR/$prog"
pidfile="$RIDELOGIC_DAEMON_PID_DIR/$prog.pid"
logfile="$RIDELOGIC_DAEMON_LOG_DIR/$prog.log"

start() {
	if [ -e "$pidfile" ]; then
		if ps -p `cat $pidfile` > /dev/null 2>&1; then
			echo $path is already running - skipping start
                        return 0
		else
			echo Lockfile $pidfile is junk. Deleting...
			rm -f $pidfile
		fi
        fi

        echo -n Starting $path
        daemon --user $RIDELOGIC_DAEMON_USER $path 
        RETVAL=$?
        echo
        return $RETVAL
}

stop() {
        RETVAL=0
	if [ -e $pidfile ]; then
		echo -n Stopping $path
                killproc $path
                RETVAL=$?
		rm -f $pidfile
	else 
		echo -n $path is not running
	fi
        echo
        return $RETVAL
}

case $2 in
	start )
                start
	        ;;
	stop )
                stop
               	;;
	restart )
		stop
		start
	        ;;
        status )
                status -p ${pidfile} $path
                ;;
	condrestart )
                if [ -f "$pidfile" ] ; then
                        stop
                        start
                fi
	        ;;
	* )
		echo "Usage: $prog (start|stop|restart|condrestart|status)"
		;;
esac
