#!/bin/sh
LNXALL_PLATSPEC=/opt/lnxall_app/platspec
export PATH=/opt/lnxall_app/bin:/opt/lnxall_app/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin

# intermediate variable for function `get_md5sum
MD5SUM_VAL=''
get_md5sum() {
	local file="$1"
	if [ ! -f "${file}" ] ; then
		MD5SUM_VAL=''
		return 1
	fi

	local md5val="$(md5sum ${file} 2>/dev/null | awk '{print $1}')"
	if [ -z "${md5val}" ] ; then
		MD5SUM_VAL=''
		return 2
	fi
	MD5SUM_VAL="${md5val}"
	return 0
}

lnxdf_systemd_inst() {
	local svrname="$1"
	local disabled="$2"
	local destdir="/usr/lib/systemd/system"

	get_md5sum "${LNXALL_PLATSPEC}/${svrname}"
	local md5_0="${MD5SUM_VAL}"
	if [ -z "${md5_0}" ] ; then
		echo "Installing '${svrname}'..."
		cp -v -f "${LNXALL_PLATSPEC}/${svrname}" "${destdir}/${svrname}" && \
			systemctl enable "${svrname}" && systemctl start "${svrname}"
		return $?
	fi

	get_md5sum "${destdir}/${svrname}"
	local md5_1="${MD5SUM_VAL}"
	if [ "${md5_0}" != "${md5_1}" ] ; then
		echo "Installing '${svrname}'..."
		if cp -v -f "${LNXALL_PLATSPEC}/${svrname}" "${destdir}/" ; then
			systemctl daemon-reload
			if [ -z "${disabled}" ]; then
				systemctl enable "${svrname}"
				systemctl start "${svrname}"
			fi
		fi
	fi
	return 0
}

systemctl stop 'emsd.service'
systemctl stop 'emud.service'
systemctl disable 'emsd.service'
systemctl disable 'emud.service'

lnxdf_systemd_inst 'alarm.service'
lnxdf_systemd_inst 'ems.service'
lnxdf_systemd_inst 'devman.service'
lnxdf_systemd_inst 'northd.service'

lnxdf_systemd_inst 'config.service'
lnxdf_systemd_inst 'procdata.service'

lnxdf_systemd_inst 'protod.service'
lnxdf_systemd_inst 'script.service'

systemctl daemon-reload

exit 0
