#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          bpinetd
# Required-Start:    $remote_fs $network
# Required-Stop:
# Default-Start:     2 3 5
# Default-Stop:      0 1 6
# Short-Description: bpinetd
# Description:       Allows the Unitrends Backup client and Unitrends
#                    appliances to communicate with one another.
### END INIT INFO

# Source function library.
failure_msg=""
success_msg=""

if [ -f /etc/init.d/functions ] ; then
	. /etc/init.d/functions
	failure_msg=echo_failure
	success_msg=echo_success
elif [ -f /etc/rc.d/init.d/functions ] ; then
	. /etc/rc.d/init.d/functions
	failure_msg=echo_failure
	success_msg=echo_success
elif [ -f /lib/lsb/init-functions ] ; then
	. /lib/lsb/init-functions
	failure_msg=log_success_msg
	success_msg=log_failure_msg
elif [ -f /etc/rc.subr ] ; then
	. /etc/rc.subr
	failure_msg=err
	success_msg=info
else
	exit 0
fi

PATH=/sbin:/bin:/usr/sbin:/usr/bin

BPINETD_BIN_PATH="/usr/local/bin/bpinetd"
pidfile="/var/run/bpinetd.pid"
RETVAL=0

uid=$(id -u)
start()
{
	# Only root can start the service
	[ $uid -ne 0 ] && exit 4

	if [ -e $pidfile ]; then
		echo -n "Process already running..."
		echo
		return 0
	fi

	echo -n "Starting bpinetd..."
	$BPINETD_BIN_PATH "start"
	RETVAL=$?

	if [ $RETVAL -eq 0 ]; then
		touch $pidfile
		chmod 644 $pidfile
		chown $2:$2 $pidfile
		echo
		return $RETVAL
	fi

	$failure_msg
	echo "Failed to start bpinetd."
	return $RETVAL
}

stop()
{
	# Only root can start the service
	[ $uid -ne 0 ] && exit 4

	echo -n "Stopping bpinetd..."
	$BPINETD_BIN_PATH "stop"
	RETVAL=$?

	if [ $RETVAL -eq 0 ]; then
		echo
		return $RETVAL
	fi

	$failure_msg
	echo "Failed to stop bpinetd."
	return $RETVAL
	$failure_msg
	echo
	return 1
}

restart()
{
	stop
	start
}

rstatus()
{
	if command -v status > /dev/null 2>&1; then
		status $BPINETD_BIN_PATH
		RETVAL=$?
	elif command -v pgrep > /dev/null 2>&1; then
		PID=$(pgrep bpinetd)
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			echo "bpinetd running, process $PID"
		fi
	elif command -v pidof > /dev/null 2>&1; then
		PID=$(pidof bpinetd)
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			echo "bpinetd running, process $PID"
		fi
	fi

	return $RETVAL
}

case "$1" in
	start | faststart)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	status)
		rstatus
		;;
	*)
		echo $"Usage: $0 {start|status|stop|restart}"
		exit 1
esac
