#!/bin/sh
export PATH=/opt/lnxall_app/bin:/opt/lnxall_app/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin
# TODO: Add post-installation instruction here, SUCH as restart service

cd /opt/lnxall_app

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
}


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

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

	get_md5sum "${destdir}/${svrname}"
	local md5_1="${MD5SUM_VAL}"

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

inst_systemd 'emsd.service'
inst_systemd 'emud.service' 1
inst_systemd 'check_history_data.service'

if [ -f platspec/script.service ] ; then
    inst_systemd 'script.service'
fi

if [ -d "/opt/lnxall_app/bin/inits" ] ; then
    #目录存在则按顺序运行目录下所有脚本
    for file in "/opt/lnxall_app/bin/inits"/*; do
        echo "Running init script ${file}..."
        chmod +x "${file}"
        "${file}"
    done
else	
    echo "No inits directory found in /opt/lnxall_app/bin/"
fi

systemctl restart emsd.service
systemctl restart check_history_data.service

systemctl disable emud.service 
systemctl stop    emud.service

exit 0
