#!/bin/sh

. /usr/bin/fonction.sh

log "...............boot.......USB........"
echo ""
echo "--- Test USB ---"

MNT_OK=0

if [ -e /dev/sda ]; then
	mount /dev/sda /mnt/usbflash	
	MNT_OK=1
fi
if [ -e /dev/sda1 ]; then
	mount /dev/sda1 /mnt/usbflash	
	MNT_OK=1
fi
if [ -e /dev/sdb ]; then
	mount /dev/sdb /mnt/usbflash	
	MNT_OK=1
fi
if [ -e /dev/sdb1 ]; then
	mount /dev/sdb1 /mnt/usbflash	
	MNT_OK=1
fi

if [ $MNT_OK != 0 ]; then	
	NBFILE=`ls /mnt/usbflash/*.tar 2> /dev/null | wc -w`
	if [ $NBFILE != 0 ]; then
		log "Update: copy .tar"
		cp /mnt/usbflash/*.tar /home/CAPELEC/DATA/update/	
		echo "copy ok"
		echo ""
	else
		echo ""
	fi

	log "save log on usb"
	mkdir /mnt/usbflash/Info/
	cp -r /home/CAPELEC/DATA/log/ /mnt/usbflash/Info/

	umount /mnt/usbflash
else
	echo "USB key not found."
	echo ""
	log ".........NO .boot.......USB........"
	log "............boot.......LAN........"

# montage du lecteur reseau
     echo "Montage du lecteur reseau GIEGLAN"
     #version normale 
     if [ $IP_MODE = DHCP ]; then
     echo "montage reseau mode dhcp"
     mount -t cifs //$IP_MACHINE/$PATH_GIEGLAN /mnt/GIEGLAN -o username=$USERNAME,password=$PASSWORD,nounix,noserverino
     else	
     echo "montage reseau mode ip fixe"
     mount -t cifs $PATH_MNT /mnt/GIEGLAN -o username=$USERNAME,password=$PASSWORD,nounix,noserverino
     fi


         
#si on ne trouve pas le dossier partagé il est possible qu'on soit en prod on va essayer de monter le dossier prod
TEST=$?
if [ $TEST = 0 ];then
#echo "PROD TEST ==0!!!!!!!!!"
		log "Mount ok"
		touch /home/CAPELEC/DATA/mount.state
		#Verification des mises à jour
		log "Check update..."
		if [ `ls /mnt/GIEGLAN/*.tar 2> /dev/null | wc -w` != 0 ]; then
			log "copy *.tar"
			cp /mnt/GIEGLAN/*.tar /home/CAPELEC/DATA/update/
			rm /mnt/GIEGLAN/*.tar
			log "copy ok"
			log ""
		else
			log "No update"	
		fi

echo "----------------------------------------"
echo "-RECHERCHE MISE A JOUR DANS GIEGLAN ----"
echo "----------------------------------------"


#Recherche sur le réseau en GIEGLAN de Start.sh
if test -e "/mnt/GIEGLAN/Start.sh"
then
#Le fichier Start.sh existe
echo "Nouvelle version Start.sh sur GIEGLAN"
cp /mnt/GIEGLAN/Start.sh /home/CAPELEC/DATA
rm /mnt/GIEGLAN/Start.sh
else
echo "Aucune version Start.sh sur GIEGLAN"
fi

else

	echo "LAN  not found."
	echo ""
	log ".........NO .boot.......LAN........"


fi
fi

echo ""
echo "--- Test update ---"

cd /home/CAPELEC/DATA/update/
NBFILE=`ls *.tar 2> /dev/null | wc -w`
if [ $NBFILE != 0 ]; then
	for numero in `seq $NBFILE`
    		do 
		FILE=`ls *.tar | head -n1`
		echo ""
		log "Update File: $FILE"
		mkdir dirtmp
		mv "$FILE" dirtmp/
		cd dirtmp
		tar -xf "$FILE"
		./update.sh
		cd ..		
		rm -r dirtmp
		echo "$FILE done"
	done	
else
	echo "No update in /home/CAPELEC/DATA"
	log "No update in /home/CAPELEC/DATA"
fi


