#!/bin/bash
if [ ! -f "/var/tmp/UPDATE_GIMINI" ]; then
        echo "/var/tmp/UPDATE_GIMINI does not exist. -> PAS D'UPDATE"
else
	echo "/var/tmp/UPDATE_GIMINI exist. -> UPDATE"

	#Si le fichier contient un nom de version on update a cette version
	# exemple gimini-0.2.28-1

	maVAR=`cat /var/tmp/UPDATE_GIMINI`
	maVERSION=`cut -c -2 /var/tmp/UPDATE_GIMINI`

        if [[ $maVERSION = "gi" ]]
	then
	 	echo "dnf -y update theox --refresh --disablerepo='*' --enablerepo=gimidepo"
                dnf -y update theox --refresh --disablerepo="*" --enablerepo=gimidepo

		echo "dnf -y update $maVAR --refresh --disablerepo='*' --enablerepo=gimidepo"
                dnf -y update $maVAR --refresh --disablerepo="*" --enablerepo=gimidepo
	
	else
	
		echo "dnf -y update theox --refresh --disablerepo='*' --enablerepo=gimidepo"
                dnf -y update theox --refresh --disablerepo="*" --enablerepo=gimidepo
		
		echo "dnf -y update gimini --refresh --disablerepo='*' --enablerepo=gimidepo"
		dnf -y update gimini --refresh --disablerepo="*" --enablerepo=gimidepo
	
	fi

	/bin/tar -xzPvf /home/system/disks/command.tar.gz

	rm -f /var/tmp/UPDATE_GIMINI

	dateMAJ=`date +"%Y-%m-%dT%H:%M:%S"`
	token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IkFETUlOIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1ODk3NiIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTg5NzYifQ.eRjvkY5L-LeoEKntbAPzmjlffkvPE9J7yJq68YHbZxU"
	nums=$(su - system /home/system/disks/s/theox/command/txserial | sed 's/[0-9]*-//g')
	nums=$(sed 's/^0*//g' <<< ${nums})
	nums=$(printf "%05d" $nums)

	idCabinet=`curl -s -X GET "https://api.timci.com/api/Cabinets/dongle/$nums" -H "accept: */*" -H "Authorization: bearer $token" | jq '.id'`
	if [[ ! $idCabinet == "null" ]]
	then
        	demandeMAJ=`curl -X GET "https://api.timci.com/api/Demandes_maj/cabinet/$idCabinet" -H "accept: */*" -H "Authorization: bearer $token"`
	        if [[ ! $demandeMAJ == "" ]]
	        then
        	        echo "Demande MAJ"
			echo $demandeMAJ
			dateMAJ=`date +"%Y-%m-%dT%H:%M:%S"`
 	               	idDemande=`echo $demandeMAJ | jq '.id'`
        	        contenuPOST=`echo $demandeMAJ | jq '.date_maj = "'$dateMAJ'"' | jq '.idUser_fait = 1'`

	                curl -X PUT "https://api.timci.com/api/Demandes_maj/$idDemande" -H  "accept: */*" -H  "Content-Type: application/json" -H "Authorization: bearer $token" -d "$contenuPOST"

        	else
	                echo "Pas de demande de MAJ"
	        fi
	fi

fi

