#!/bin/sh

BP_PID=/var/run/bpinetd.pid
MACHINE=`uname`

if [ -e ${BP_PID} ]; then
	pkill -term -x bpinetd
	rm -f ${BP_PID}
fi

install --mode=0755 -D /usr/bp/bin/bpinetd /usr/local/bin/

if (command -v pkg-config && pkg-config systemd) > /dev/null 2>&1; then
	SYSTEMD_SYSTEM_UNIT_DIR=$(pkg-config systemd --variable=systemdsystemunitdir)
	if [ -d "${SYSTEMD_SYSTEM_UNIT_DIR}" ]; then
		install --mode=0644 /usr/bp/bpinetd.service ${SYSTEMD_SYSTEM_UNIT_DIR}
	fi
else
	install --mode=0755 /usr/bp/bin/bpinetd_rc_script /etc/init.d/bpinetd
fi

if command -v systemctl > /dev/null 2>&1; then
	systemctl enable bpinetd > /dev/null 2>&1
	systemctl start bpinetd > /dev/null 2>&1
elif command -v initctl > /dev/null 2>&1; then
	install --mode=0644 /usr/bp/bpinetd.conf /etc/init/
elif command -v update-rc.d > /dev/null 2>&1; then
	update-rc.d bpinetd start 50 2 3 4 5 . stop 50 0 1 6 .
elif command -v chkconfig > /dev/null 2>&1; then
	chkconfig --add bpinetd
else
	if [ $MACHINE != "FreeBSD" ]; then
	# Install for runlevels 2, 3, 5
		for i in 2 3 5; do
			if [ -d $(readlink -e /etc/rc${i}.d/) ]; then
				ln -s /etc/init.d/bpinetd /etc/rc${i}.d/S50bpinetd > /dev/null 2>&1
				ln -s /etc/init.d/bpinetd /etc/rc${i}.d/K50bpinetd > /dev/null 2>&1
			elif [ -d $(readlink -e /etc/rc.d/rc${i}.d/) ]; then
				ln -s /etc/init.d/bpinetd /etc/rc.d/rc${i}.d/S50bpinetd > /dev/null 2>&1
				ln -s /etc/init.d/bpinetd /etc/rc.d/rc${i}.d/K50bpinetd > /dev/null 2>&1
			fi
		done
	fi
fi

if [ ! -e ${BP_PID} ]; then
	/usr/local/bin/bpinetd start
fi

exit
