#!/bin/sh

CONFIG_BT=0	# 0 ou 1
TYPE=USB 	#FTP ou USB

## BOSCH ##
VERSION_NEW="V1.10"
DATE_NEW="08/06/2018"

echo "******************************************************************"
echo "*******    Update run...	****************************************"
echo "******************************************************************"

gpio dirout 80
gpio dirout 81
gpio dirin 82


cd /home/CAPELEC/DATA/update/dirtmp/


VERSION_BACK=`cat "/etc/info" | grep "VERSION" | cut -d"=" -f2 `


if [ $? = 0 ]; then
	echo "update OK"	
	echo "export VERSION=$VERSION_NEW" > /etc/info
	echo "export DATE=$DATE_NEW" >> /etc/info
	echo "export INFORMATION=" >> /etc/info

	gpio clear 80

	sleep 1
	gpio set 80

	sleep 1
	gpio clear 80
	sleep 1

	rm /etc/init.d/S54openvpn
	mv /etc/openvpn/client.conf clientold.conf

	cp root /var/spool/cron/crontabs/
	cp crontabs.1358 /var/spool/cron/


	cp SAVE_PARAM.cgi /var/www/CONFIGURATION/
	cp SAVE_PARAM.cgi /var/wwwcapelec/CONFIGURATION/

	killall majdist.sh
	cp majdist.sh /usr/bin/	

	killall 1830
	cp 1830 /usr/bin/

	killall 1830_prod
	cp 1830_prod /usr/bin/

	SERIAL=`cat "/home/CAPELEC/DATA/PARAM.txt" | grep "#020#" | cut -d"#" -f3 | tr -d " "`
	echo "SERIAL=$SERIAL"
	if [ -z $SERIAL ]; then
		echo "ERROR: SERIAL is null"	
		exit
	fi

	sed "s/200/$SERIAL/" /etc/board_id > /etc/board_id_TMP
	cp /etc/board_id_TMP  /etc/board_id

	#pour parametrage auto BT
	if [ $CONFIG_BT = 1 ]; then
		sed "s/RS232/BLUETOOTH/" /home/CAPELEC/DATA/PARAM.txt > /home/CAPELEC/DATA/PARAMTMP.txt
		cp /home/CAPELEC/DATA/PARAMTMP.txt  /home/CAPELEC/DATA/PARAM.txt
	fi

	#Info fichier serveur FTP
	BRAND=`cat "/home/CAPELEC/DATA/PARAM.txt" | grep "#005#" | cut -d"#" -f3 | tr -d "1 \""`
	echo "BRAND=$BRAND"
	SERIAL=`cat "/home/CAPELEC/DATA/PARAM.txt" | grep "#020#" | cut -d"#" -f3 | tr -d " "`
	echo "SERIAL=$SERIAL"
	MODEL="CAP1830"
	echo "MODEL=$MODEL"

	NAME_FILE="$MODEL-$BRAND-$VERSION_NEW-SN$SERIAL-BACK$VERSION_BACK-$TYPE"
	echo $NAME_FILE > /home/CAPELEC/DATA/sendtoftp.state

	echo "MISE A JOUR OK LE SYSTEME VA REMEDARRER DANS 3 SECS"

	if [ $CONFIG_BT = 1 ]; then
		touch /mnt/usbflash/done_Config_BT_CAPELEC_$NAME_FILE
	fi

else
	echo "update NOK!!!!"	
	VERSION=`cat /etc/info | grep VERSION`
	DATE=`cat /etc/info | grep DATE`
	
	echo "$VERSION" > /etc/info
	echo "$DATE" >> /etc/info
	echo "export INFORMATION=Update Error" >> /etc/info
fi


	gpio clear 80
	gpio clear 81
	sleep 1
	gpio set 80
	gpio set 81
	sleep 1
	gpio clear 80
	gpio clear 81
	sleep 1
	gpio set 80
	gpio set 81
	sleep 1
	gpio clear 80
	gpio clear 81
	sleep 1
	gpio set 80
	gpio set 81
	sleep 1
	gpio clear 80
	gpio clear 81


if [ $TYPE = USB ]; then
	#halt pour MAJ localy
	halt
else
	#reboot pour MAJ A DISTANCE
	reboot
fi		


