#!/bin/sh
if [ ! -d "/tmp/fm" ]; then
	exit
fi;

kill `pidof webui`
kill `pidof bacnetrouter`
kill `pidof gateway`

rm /tmp/fm/upgrade

if [ -e /tmp/fm/fwuldl ] && [ -e /tmp/fm/uart2040.fwm ]; then
	/tmp/fm/fwuldl 0 d < /tmp/fm/uart2040.fwm || (reboot && sleep 100)
	rm /tmp/fm/fwuldl /tmp/fm/uart2040.fwm
fi;

cp /root/login.conf /tmp/fm
cp /root/license.conf /tmp/fm

for var in "$@"
do
	if test $var = "delcfg"
	then
                delcfg=$var
		break
	fi
done
        
JSON=$(/tmp/fm/res485 /tmp/fm/resource.conf)
echo $JSON > /tmp/fm/resource.conf
rm /tmp/fm/res485

JSON=$(/tmp/fm/chkres /tmp/fm/resource.conf /tmp/fm/network.conf)
echo $JSON > /tmp/fm/network.conf
cp /tmp/fm/network.conf /tmp/fm/network.conf.bak

if test -z $delcfg
then
	cp /root/app.conf /tmp/fm
	cp /root/update.conf /tmp/fm
	cp /root/network.conf /tmp/fm
	JSON=$(/tmp/fm/chkres /tmp/fm/resource.conf /tmp/fm/network.conf)
	echo $JSON > /tmp/fm/network.conf
fi

rm /tmp/fm/chkres
mv /tmp/fm/99-ntpflag /etc/hotplug.d/ntp/

rm -rf /root/*
mv /tmp/fm/* /root/

reboot
