#!/bin/sh

install_file()
{
	src="$1"
	dest="$2"

	if [ -e "$dest" ] && ! cmp --quiet "$src" "$dest"
	then
		echo "INFO: $dest exists, new version copied to ${dest}.new"
		cp "$src" "${dest}.new"
		return 1
	fi

	cp "$src" "${dest}"
	return 0
}


echo "--- hyperion ambient light postinstall ---"
echo "- install configuration template"
mkdir -p /etc/hyperion

HYPERION_RUNNING=false
pgrep hyperiond > /dev/null 2>&1 && HYPERION_RUNNING=true

start_msg=""
restart_msg=""
SERVICE_POSTFIX=""

if grep -m1 systemd /proc/1/comm > /dev/null
then
	echo "- init deamon: systemd"
	# systemd
	$HYPERION_RUNNING && systemctl stop hyperion 2> /dev/null
	install_file /usr/share/hyperion/service/hyperion.systemd.sh /etc/systemd/system/hyperiond.service || SERVICE_POSTFIX=".new"
	systemctl -q enable hyperiond.service
	start_msg="systemctl start hyperion"
	$HYPERION_RUNNING && systemctl start hyperiond

elif [ -e /sbin/initctl ]
then
	echo "- init deamon: upstart"
	# upstart
	$HYPERION_RUNNING && initctl stop hyperiond
	install_file /usr/share/hyperion/service/hyperiond.initctl.sh /etc/init/hyperion.conf || SERVICE_POSTFIX=".new"
	initctl reload-configuration
	start_msg="initctl start hyperion"
	$HYPERION_RUNNING && initctl start hyperiond

else
	echo "- init deamon: sysV"
	# sysV
	$HYPERION_RUNNING && service hyperiond stop 2>/dev/null
	install_file /usr/share/hyperion/service/hyperion.init.sh /etc/init.d/hyperiond || SERVICE_POSTFIX=".new"
	chmod +x /etc/init.d/hyperiond
	update-rc.d hyperiond defaults 98 02
	start_msg="service hyperion start"
	$HYPERION_RUNNING && service hyperiond start
fi

echo "-----------------------------------------------------------------------------"
echo "- hyperion is installed, please check your configuration in /etc/hyperion/  -"
echo "-----------------------------------------------------------------------------"

if [ -e /opt/hyperion/ ]
then
	echo
	echo "---------------------------------------------------------------------------------"
	echo "- It seemd that you have an older version of hyperion installed in /opt/hyerion -"
	echo "- please remove it and check your config to avoid problems                      -"
	echo "---------------------------------------------------------------------------------"
fi