#!/bin/sh

# Start/stop/restart/reload ndo2db
# Copyright (c) 2016 Nagios(R) Core(TM) Development Team

BSDTYPE=@dist_type@

NDO2DB_BIN=@sbindir@/ndo2db
NDO2DB_CFG=@pkgsysconfdir@/ndo2db.cfg
PID_DIR=@piddir@
PID_FILE=@piddir@/ndo2db.pid

# Get PID of running process
ndo2db_get_pid() {
	if [ -r "$PID_FILE" ]; then
		pid1=$(cat "$PID_FILE")
	else
		pid1=""
	fi
	pid2=$(ps -A -o pid,command | grep ndo2db | grep -v grep | tr -s ' ' | sed -e 's/^ //' | cut -d' ' -f1)

	if [ $pid1 = $pid2 ]; then
		echo $pid1
	else
		echo $pid1 $pid2
	fi
}

# Start ndo2db
ndo2db_start() {
	printf "Starting ndo2db daemon: $NDO2DB_BIN - "
	if [ ! -d "$PID_DIR" ]; then
		mkdir -p "$PID_DIR"
	fi
	$NDO2DB_BIN -c $NDO2DB_CFG
	if [ $? = 0 ]; then
		echo "started"
	else
		echo "failed"
	fi
}

# Stop ndo2db
ndo2db_stop() {
	printf "Stopping ndo2db daemon - "
	pid=`ndo2db_get_pid`
	if [ -n "$pid" ]; then
		kill $(cat "$PID_FILE")
		if [ $? = 0 ]; then
			echo "stopped"
		else
			echo "failed"
		fi
	else
		echo "Does not appear to be running"
	fi
}

# Restart ndo2db
ndo2db_restart() {
	ndo2db_stop
	sleep 1
	ndo2db_start
}

# ndo2db status
ndo2db_status() {
	pid=`ndo2db_get_pid`
	if [ -n "$pid" ]; then
		if [ $BSDTYPE = aix ]; then
			echo "ndo2db is running ($pid)"
		elif ps -C ndo2db >/dev/null; then
			echo "ndo2db is running ($pid)"
		else
			echo "ndo2db is stopped."
		fi
	else
		echo "ndo2db is stopped."
	fi
}

case "$1" in
'start')
	ndo2db_start
	;;
'stop')
	ndo2db_stop
	;;
'restart')
	ndo2db_restart
	;;
'status')
	ndo2db_status
	;;
*)
	echo "Usage $0 start|stop|restart|status"
	;;
esac
