#!/bin/bash


#/**
#         updateCache
#@brief   Actualiza la cache del cliente con imagen o fichero iso.
#@param 1 REPO          Origen del fichero. -accesible por nfs-samba-
#@param 2 str_fichero   nombre del fichero a actualizar.
#@param 3 str_protoco.  TORRENT | MULTICAST    | UNICAST.
#@param 4 str_opcionesprotocolo
#@param 4 str_opcionesupdatecache
#@ejemplo: oneRemoteFromMaster 172.17.36.11 CACHE /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop 
#@return  
#@exception OG_ERR_FORMAT     formato incorrecto.
#@note   
#@todo: 
#@version 0.9.1 - integracion EAC
#@author  Antonio J. Doblas Viso. Universidad de Malaga.
#@date    2008/03/17
#@version 0.9.2 - integracion OpenGnsys
#@author  Antonio J. Doblas Viso. Universidad de Malaga.
#@date    2010/07/27
#@version 1.0.1 - Control de espacio requerido
#@author  Antonio J.Doblas Viso
#@date   2011-05-10
#*/ ##

PROG="$(basename $0)"
if [ $# -lt 3 ]; then
    ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG str_REPO _str_Relative_Path_OGIMG_with_/ PROTOCOLO OPCIONES_PROTOCOLO OPCIONES_UPDATECACHE"
    exit $?
fi

REPOSITORIO="$1"
PROTOCOLO="$3"
OPTPROTOCOLO="$4"
REPOIP=$(ogGetRepoIp)
echo $REPOSITORIO $REPOIP $PROTOCOLO $OPTPROTOCOLO
# Si el repositorio local CACHE no existe salimos.
if ! $(ogFindCache >/dev/null); then
        ogRaiseError $OG_ERR_NOTCACHE "CACHE"
        exit $?
fi

#Comprobamos si Actualizacion - existe una imagen con igual nombre pero distinto sum-
#TODO: ogUpdateCacheIsNecesary debe borrar la imagen que tenga igual nombre pero distinto sum-
ogUpdateCacheIsNecesary $1 $2; RETVAL=$?
# si RETVAL=0 => actualizamos  si RETVAL=1 no actaulizasmo-exit 0  || si RETVAL>2 exit 1
[ "$RETVAL" == "1" ] && exit 0
[ "$RETVAL" -gt  "1" ] && exit 1


CACHESIZEFREE=$(ogGetFreeSize `ogFindCache`)
FILESIZE=$(ls -sk $(ogGetPath $REPOSITORIO "$2") | cut -f1 -d" ")

if [ "$FILESIZE" -ge "$CACHESIZEFREE" ]  
then
	echo "el tamanio del fichero $2 = $FILESIZE es mayor que el espacio dispinible en la cache = $CACHESIZEFREE"
	ogRaiseError $OG_ERR_CACHESIZE "CACHE"
    exit $?
fi

ogUpdateCacheIsNecesary $REPOSITORIO "$2"; RETVAL=$?
# si RETVAL=0 => actualizamos  si RETVAL=1 no actaulizasmo-exit 0  || si RETVAL>2 exit 1
[ "$RETVAL" == "1" ] && exit 0
[ "$RETVAL" -gt  "1" ] && exit 1

ogMountCache >/dev/null

## Si no existe, crear subdirectorio para el fichero en la cache.
IMGDIR=$(ogGetParentPath CACHE "/$2")
if [ $? != 0 ]; then
    echo "[5] Crear subdirectorio del fichero  \"$2 $(dirname "$2")."
    ogMakeDir CACHE $(dirname "/$2")
    IMGDIR=$(ogGetParentPath CACHE "/$2") || exit $?
fi


case "$PROTOCOLO" in
	torrent | TORRENT )
		echo "ogCopyFile $1 $2.torrent absolute $OGCAC/$OGIMG"
		# tiempos 
		timewait=$(expr $(printf '%d\n' 0x$(ogGetMacAddress | awk -F: '{print $5$6}')) \* 120 / 65535)                         
		ogCopyFile $REPOSITORIO "$2.torrent" "$IMGDIR"
		#TODO: comprobar que el tracker definido en el fichero es correcto.
    	#TODO comprobar que el fichero torrent está en cache
		# retardamos el inicio -aleatorio de 0 a 120 segundos- al tracker para gestionar mas de +-40 equipos 
		P2PWAIT=$[ ( $RANDOM % 120 )  + 1 ]
		echo "Esperando $P2PWAIT segundos para iniciar ogTorrentStart CACHE $2.torrent $4"
		sleep $P2PWAIT
		ogTorrentStart CACHE "$2.torrent" $4
	;;
	multicast | MULTICAST )
		echo "determinando puerto principal y auxiliar."
		PORT=$(echo $OPTPROTOCOLO | cut -f1 -d":")
		let PORTAUX=$PORT+1
        #TODO: ticket 379
		NUMBER=$[ ( $RANDOM % 30 )  + 1 ]
		sleep $NUMBER
		#FIN TODO
		echo "comprobando puerto $PORTAUX en $REPOIP (sesion multicast en puerto $PORT) "
		if (nmap -n -sU -p $PORTAUX $REPOIP | grep open)
		then 
	   		ogMcastReceiverFile $PORT CACHE "$2"
		else
		    # TODO ticket 379 Realizar la petición basada en identificador de operacion
	   		echo "solicita la apertura:  hose $REPOIP 2009 --out sh -c "echo -ne START_MULTICAST $2 $OPTPROTOCOLO""
	   		hose $REPOIP 2009 --out sh -c "echo -ne START_MULTICAST $2 $OPTPROTOCOLO"
	   		#echo "espero y llamo a: ogMcastReceiverFile $PORT CACHE $2"
	   		sleep 10
	   		if (nmap -n -sU -p $PORTAUX $REPOIP | grep open)
	   		then 
	   			ogMcastReceiverFile $PORT CACHE "$2"
			else
			    echo "la peticion ha fallado: hose $REPOIP 2009 --out sh -c echo -ne START_MULTICAST $2 $OPTPROTOCOLO"
	   		    exit 1
	   		fi
		fi	
	;;
	unicast | UNICAST )
		echo "unicast"
		ogCopyFile $REPOSITORIO "$2" "$IMGDIR"
	;;
esac


ogUpdateCacheIsNecesary $REPOSITORIO "$2"; RETVAL=$?
# si RETVAL=0 => actualizamos  si RETVAL=1 no actaulizasmo-exit 0  || si RETVAL>2 exit 1
[ "$RETVAL" == "0" ] && exit 1
[ "$RETVAL" == "1" ] && exit 0
[ "$RETVAL" -gt  "1" ] && exit 1

