#!/bin/sh
#  Check to see whether service scripts in /etc/init.local are up to date:
#   • remove old-style "default" daemons
#   • remove old-style network interface service scripts
#   • update new-style versioned scripts from templates
#
#  Copyright: ©2010, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#



# first Platinum editions had a different mechanism for running standard
# system daemons that is incompatible with what we use now, so remove it
if [ -e "/etc/init.local/data-mux-gcf.default" ]
then
	echo ' * Removing old "default" daemons'
	rm /etc/init.local/*.default
	grep -v '\.default$' < "/etc/init.local/autostart" > "${tmpfile}"
	cp "${tmpfile}" "/etc/init.local/autostart"
fi



# remove old-style net init.local scripts
for NETSCRIPT in /etc/init.local/net_*
do
	[ -e "${NETSCRIPT}" ] || continue
	grep -q dh_args "${NETSCRIPT}" || continue
	echo " * Removing ${NETSCRIPT} for upgrade to new version"
	rm "${NETSCRIPT}"
done



# perform upgrade of an initscript, given old instance and template (basically
# sources the old instance to get variable values and then re-instantiates the
# template with the new values)
upgrade_initscript() {
	service="$1"
	svc_template="$2"
	initscript="$3"

	echo "  - upgrading ${initscript} from ${local_version} to ${template_version}"
	(
		. "${initscript}"
		[ -z "${MYLISTING}" ] && MYLISTING="${service} unnamed instance"
		sed 	-e "s,@@NAME@@,${service},g" \
			-e "s,@@DESC@@,${MYLISTING},g" \
			-e "s,@@CFGFILE@@,${MYCFG},g" \
			"${svc_template}" > "${initscript}"
		chmod 0755 "${initscript}"
	)
}



# check to see if an instance of an initscript is up to date compared to the
# template; if not, pass to upgrade_initscript to perform actual upgrade
check_initscript() {
	service="$1"
	svc_template="$2"
	initscript="$3"

	# check if the new template is versioned; if not, ignore this
	template_version="$( . ${svc_template} && echo "${MYVERSION}")"
	[ -z "${template_version}" ] && return 0

	# get the currently-installed version
	local_version="$( . ${initscript} && echo "${MYVERSION}")"
	[ -z "${local_version}" ] && local_version="(pre-versioned)"

	# test if currently-installed version is up to date
	if [ "${local_version}" != "${template_version}" ]
	then
		upgrade_initscript "${service}" "${svc_template}" "${initscript}"
	fi
}



# run the upgrade procedure
echo " * Ensuring service scripts are up to date"

cd /usr/share/config-base/services
for service in *
do
	svc_template="./${service}/svc-script.in"
	[ -e "${svc_template}" ] || continue

	for initscript in /etc/init.local/${service}.*
	do
		[ -e "${initscript}" ] || continue
		check_initscript ${service} ${svc_template} ${initscript}
	done
done
