#!/bin/sh
#filepath="/home/kk"
filepath="/app/ccuApps"
/etc/init.d/S90dcron stop
if [ ! -f "/sbin/jq" ]
then
   cp $filepath/jq /sbin
fi
if [ -f "/app/nx5Apps/syscfg.json" ]
then
	if [ ! -f "/data/syscfg.json" ]
	then
		cp /app/nx5Apps/syscfg.json /data	
	fi
	embbedflag=`cat /data/syscfg.json|jq ."ccuembbed"`
        #embbedflag="0"
	echo $embbedflag
	if [ "$embbedflag" = '"0"' ] 
	then
		echo "do not start the ccu process"
		exit 0
	fi	
fi
ccuid_hostname=`fw_printenv | grep uuid |cut -d '=' -f 2`;
curr_hostname=`cat /etc/hostname`;

if [ "$ccuid_hostname" != "$curr_hostname" ]; then
   	echo "$ccuid_hostname" > /etc/hostname
   	hostname $ccuid_hostname
	/etc/init.d/S01rsyslogd restart
fi
nanomsg_File="$filepath/lib/libnanomsg.so.5"
ev_File="$filepath/lib/libev.so.4"
sqlite_File="$filepath/lib/libsqlite3.so.0"

run_Dir="/data/kk"
tsl_Dir="${run_Dir}/tsl"
map_Dir="${run_Dir}/map"
smt_Dir="/etc/smarthome"
#dev_cfg_Dir="${run_Dir}/dev_config_table"

#cd /sbin/
#insmod /sbin/ssd1306-revision.ko
#/sbin/oled >/dev/null 2>&1 &
#sleep 1
if [ ! -d "$smt_Dir" ]; then
	mkdir ${smt_Dir}
fi
if [ ! -d "$run_Dir" ]; then
	mkdir ${run_Dir}
fi

if [ ! -d "$tsl_Dir" ]; then
	cp -rf $filepath/tsl ${run_Dir}/
else
	if [ ! -f "${run_Dir}/tsl/version" ]; then
		cp -rf $filepath/tsl ${run_Dir}/
	else	
		defaultVer=`cat ${filepath}/tsl/version`
		curVer=`cat ${run_Dir}/tsl/version`
		if [ $defaultVer != $curVer ]; then
			cp -rf $filepath/tsl ${run_Dir}/
		fi
	fi
fi
#if [ ! -d "$map_Dir" ]; then
cp -rf $filepath/map ${run_Dir}/
#fi

cd $filepath/lib
if [ ! -f "$nanomsg_File" ]; then
	ln -sf $filepath/lib/libnanomsg.so /lib/libnanomsg.so.5
fi
if [ ! -f "$ev_File" ]; then
	ln -sf $filepath/lib/libev.so /lib/libev.so.4
fi

if [ ! -f "$sqlite_File" ]; then
	ln -sf $filepath/lib/libsqlite3.so /lib/libsqlite3.so.0
fi


export LD_LIBRARY_PATH=$filepath/lib

$filepath/bin/kk_midware &
sleep 1
$filepath/bin/kk_lan --uart=/dev/ttyS3&
sleep 2
$filepath/bin/kk_cloud &
sleep 5
$filepath/bin/smarthome_z3gw_nx5 -r0 -l3 --device-def=$filepath/config/kk_device_def.json --db=/data/kk/kk_z3gw.db --uart=/dev/ttyS1&
sleep 1
if [ ! -f /etc/cron.d/ccu ]; then
	echo "*/1 * * * *   /app/ccuApps/script/process_check.sh" > /etc/cron.d/ccu || { echo "ERROR:add ccu crontab rule failed."; exit 1;}
fi
/etc/init.d/S90dcron restart
ntpd -n -q -d -p stdtime.gov.hk &
exit 0