#!/bin/sh
#
# nginx_exporter     Start/Stop the nginx_exporter daemon
#
# chkconfig: - 80 20
# description: nginx_exporter is a metrics daemon for Prometheus.
# processname: nginx_exporter

### BEGIN INIT INFO
# Provides: nginx_exporter
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/Stop the nginx_exporter daemon
# Description: nginx_exporter is a metrics daemon for Prometheus.
### END INIT INFO

# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
fi

# defaults
FLAGS=""

# config
if [ -f "{{ nginx_exporter_config_file }}" ] ; then
  . "{{ nginx_exporter_config_file }}"
fi

RETVAL=0

# Set up some common variables before we launch into what might be
# considered boilerplate by now.
prog="{{ nginx_exporter_program }}"
name="$(basename $prog)"
binary="$(readlink -f $prog)"
lockfile="/var/lock/subsys/$name"
logdir="{{ nginx_exporter_log_path }}"
pidfile="{{ nginx_exporter_pid_path }}/$name.pid"
user="{{ nginx_exporter_user }}"
group="{{ nginx_exporter_group }}"

start() {
	[ -r $binary ] || exit 5
	[ -d $logdir ] || (
		mkdir -p $logdir
		chmod 0750 $logdir
		chown $user:$group $logdir
	)
	echo -n $"Starting $name: "
	export DATA_SOURCE_NAME
	daemonize -a -c '/' -e ${logdir}/${name}.err.log -o ${logdir}/${name}.out.log \
		-p $pidfile -l $lockfile -u $user \
		$prog $OPTIONS
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch $lockfile
	return $RETVAL
}

stop() {
	echo -n $"Stopping $prog: "
	killproc -p $pidfile $binary
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f $lockfile
	return $RETVAL
}

restart() {
	stop
	start
}

reload() {
	restart
}

force_reload() {
	restart
}

rh_status() {
	# run checks to determine if the service is running or use generic status
	status -p $pidfile -l $lockfile $binary
}

rh_status_q() {
	rh_status >/dev/null 2>&1
}

case "$1" in
  start)
	rh_status_q && exit 0
	start
	;;
  stop)
	rh_status_q || exit 0
	stop
	;;
  restart)
	restart
	;;
  reload)
	rh_status_q || exit 7
	reload
	;;
  force-reload)
	force_reload
	;;
  status)
	rh_status
	;;
  condrestart|try-restart)
	rh_status_q || exit 0
	restart
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
	exit 2
esac

exit $?
