#!/bin/bash
# Scirpt de ejemplo para restaurar una imagen.
# (puede usarse como base para el programa de restauración de imágenes usado por OpenGNSys Admin).

TIME1=$SECONDS
PROG="$(basename $0)"
if [ $# -lt 4 ]; then
    ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]"
    exit $?
fi

#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE"
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg

# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp

echo "[1] $MSG_SCRIPTS_START $0 $*" | tee -a $OGLOGSESSION $OGLOGFILE

# Procesar parámetros de entrada
REPO="${1^^}"
IMGNAME="$2"
DISK="$3"
PART="$4"
PROTO="${5^^}"
PROTO=${PROTO:-"UNICAST"}
PROTOOPT="$6"
IMGTYPE="${IMGTYPE:-"img"}"
# Comprobar que existe la imagen del origen.
IMGFILE=$(ogGetPath "$REPO" "$IMGNAME.$IMGTYPE") || ogRaiseError $OG_ERR_NOTFOUND "$REPO, ${IMGNAME%/*}" || exit $?
IMGDIR=$(ogGetParentPath "$REPO" "$IMGNAME") || ogRaiseError $OG_ERR_NOTFOUND "$REPO, ${IMGNAME%/*}" || exit $?

# Procesar protocolos de transferencia.
case "$PROTO" in
    UNICAST|UNICAST-DIRECT)
        # Restaurar la imagen.
        echo "[40] ogRestoreImage $REPO $IMGNAME $DISK $PART UNICAST"
        ogRestoreImage "$REPO" "$IMGNAME" "$DISK" "$PART" UNICAST | tee -a $OGLOGCOMMAND
        RETVAL=${PIPESTATUS[0]}
        ;;
    MULTICAST|MULTICAST-DIRECT)
        PORT=$(echo $PROTOOPT | cut -f1 -d":")
        TOOL=$(ogGetImageProgram REPO $IMGNAME)
        COMPRESS=$(ogGetImageCompressor REPO $IMGNAME)
        #TODO comprobar parametros anteriores
        ogMcastRequest "$IMGNAME.img" "$PROTOOPT"
        ogMcastReceiverPartition "$DISK" "$PART" "$PORT" "$TOOL" "$COMPRESS" | tee -a $OGLOGCOMMAND
        RETVAL=${PIPESTATUS[0]}
        ;;
    *)  # Protocolo desconocido.
        ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones ]"
        exit $?
esac

TIME=$[SECONDS-TIME1]
echo "[100] Duracion de la operacion $[TIME/60]m $[TIME%60]s"

# Código de salida del comando prinicpal de restauración.
exit $RETVAL

