#!/bin/bash
### BEGIN INIT INFO
# Provides:          glpi-agent
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop glpi-agent program
### END INIT INFO
#
# ::do_not_edit::
# ::maintainer::
#
# ::copy::
#
# v1.1 (2024-01-24)
#
set -e -u

PROGNAME="glpi-agent"
DESC="[ku] GLPI Agent"
DAEMON="/usr/bin/glpi-agent"

# init options
#
ENABLE="false"
OPTIONS=''

test -x $DAEMON || exit 0

. /lib/lsb/init-functions
. /etc/default/rcS

default="/etc/default/$PROGNAME"

[ -s $default ] && {
  . $default
  case "$ENABLE" in
    true|false)	;;
    inetd)	exit 0 ;;
    *)
    	log_failure_msg "$default: \$ENABLE must be 'true', 'false' or 'inetd', $DAEMON not started"
	exit 1
	;;
  esac
}

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

do_start()
{
	local rc=0

	$ENABLE || return 0

	is_running && {
		log_warning_msg "daemon $DAEMON already running"
		return 0
	}

        log_daemon_msg "Starting $DESC" "$PROGNAME"

	$DAEMON --daemon --pidfile=/var/run/$PROGNAME.pid \
		--logger=Syslog \
		$OPTIONS || {
		rc=$?
                log_end_msg 1
                rm -f /var/run/$PROGNAME.pid
		return $rc
	}

        log_end_msg 0
	return 0
}


do_stop()
{
	if is_running
	then
        	log_daemon_msg "Stopping $DESC" "$PROGNAME"
		start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/$PROGNAME.pid
		sleep 1
		if is_running
		then
        		log_end_msg 1
		else
			log_end_msg 0
		fi
	else
		log_warning_msg "daemon $DAEMON is not running"
	fi
	rm -f /var/run/$PROGNAME.pid
	return 0
}



is_running()
{
	local running=
	running=$(ps axwww | grep " $PROGNAME" | fgrep -v grep)
	[ "X$running" = "X" ] && return 1
	return 0
}


case "$1" in
  start)	do_start ;;
  stop)		do_stop ;;
  restart)
  	do_stop
	sleep 2
	do_start
	;;
  reload|force-reload)
        #log_warning_msg "reloading $PROGNAME daemon: not needed, as the daemon re-reads the configs every run"
	do_stop
	do_start
	;;
  status)
	if is_running
	then
		echo "$PROGNAME is running"
	else
		echo "$PROGNAME is not running"
	fi
	;;
  *)
	echo "usage: /etc/init.d/$PROGNAME {start|stop|reload|force-reload|restart|status}"
	exit 1
esac

exit 0
