#!/bin/sh
#filepath="/home/kk"
filepath="/app/ccuApps"
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

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"
#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 "$run_Dir" ]; then
	mkdir ${run_Dir}
fi

#if [ ! -d "$tsl_Dir" ]; then
cp -rf $filepath/tsl ${run_Dir}/
#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/kk_device_def.json --db=/data/kk/kk_z3gw.db --uart=/dev/ttyS1&
sleep 2
$filepath/bin/kk_lan --uart=/dev/ttyS3&
sleep 1
if [ ! -f /etc/cron.d/ccu ]; then
	echo "*/1 * * * *   /app/ccuApps/process_check.sh" > /etc/cron.d/ccu || { echo "ERROR:add ccu crontab rule failed."; exit 1;}
fi
ntpd -n -q -d -p stdtime.gov.hk &
exit 0