#!/bin/sh

cd /home/souti/dev-domoticz/
# This script can be used to upgrade/compile to the latest version
# Please not that all modifications on the original files are lost

echo "Updating to server revision..."

json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=3&svalue=Update_en_cours"
#echo "HUM " $json >>/var/log/syslog
curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog

git fetch --all
if [ $? -ne 0 ]
then
        json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=4&svalue=Git_a_echoue"
        #echo "HUM " $json >>/var/log/syslog
        curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog
	exit 1
fi
git reset --hard origin/master

json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=3&svalue=Fetch_Git_Termine"
#echo "HUM " $json >>/var/log/syslog
curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog

cmake -DCMAKE_BUILD_TYPE=Release .
if [ $? -ne 0 ]
then
	echo "CMake failed!";
        json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=4&svalue=CMake_a_echoue"
        #echo "HUM " $json >>/var/log/syslog
        curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog
	exit 1
fi

json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=2&svalue=Compilation_en_cours"
#echo "HUM " $json >>/var/log/syslog
curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog
make
if [ $? -ne 0 ]
then
	echo "Compile failed!";
        json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=3&svalue=Compilation_a_echoue"
        #echo "HUM " $json >>/var/log/syslog
        curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog
	exit 1
fi
# Restart domoticz
#echo "Restarting Domoticz... (please standby...)"
#sudo service domoticz.sh restart
version=`cat appversion.h  |grep APPVERSION |awk -F " " '{print $3}'`
json="http://localhost:81/json.htm?type=command&param=udevice&idx=89&nvalue=1&svalue=Nouvelle_version_disponible_$version"
#echo "HUM " $json >>/var/log/syslog
curl -s -i -H "Accept: application/json" $json >/dev/null 2>>/var/log/syslog
