#!/bin/bash

MN_PID=/var/run/mynotify.pid

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

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

mkdir -p /usr/bp/incremental_forever

if (command -v pkg-config && pkg-config systemd) &> /dev/null; then
	SYSTEMD_SYSTEM_UNIT_DIR=$(pkg-config systemd --variable=systemdsystemunitdir)
	if [ -d ${SYSTEMD_SYSTEM_UNIT_DIR} ]; then
		install --mode=0644 /usr/bp/mynotify.service ${SYSTEMD_SYSTEM_UNIT_DIR}
	fi
elif (command -v systemctl && test -d /lib/systemd/system) &> /dev/null; then
	install --mode=0644 /usr/bp/mynotify.service /lib/systemd/system
elif (command -v systemctl && test -d /usr/lib/systemd/system) &> /dev/null; then
	install --mode=0644 /usr/bp/mynotify.service /usr/lib/systemd/system
else
	install --mode=0755 /usr/bp/bin/notify_fs_event /etc/init.d/mynotify
fi

if command -v systemctl &> /dev/null; then
	systemctl enable mynotify &> /dev/null
	systemctl start mynotify &> /dev/null
elif command -v initctl &> /dev/null; then
	install --mode=0644 /usr/bp/mynotify.conf /etc/init/
elif command -v update-rc.d &> /dev/null; then
	update-rc.d mynotify start 50 2 3 5 . stop 50 0 1 6 .
elif command -v chkconfig &> /dev/null; then
	chkconfig --add mynotify
else
	# 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/mynotify /etc/rc${i}.d/S50mynotify &> /dev/null
			ln -s /etc/init.d/mynotify /etc/rc${i}.d/K50mynotify &> /dev/null
		elif [ -d $(readlink -e /etc/rc.d/rc${i}.d/) ]; then
			ln -s /etc/init.d/mynotify /etc/rc.d/rc${i}.d/S50mynotify &> /dev/null
			ln -s /etc/init.d/mynotify /etc/rc.d/rc${i}.d/K50mynotify &> /dev/null
		fi
	done
fi

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

exit
