#!/bin/bash

#/**
#@file    createImage
#@brief   Scirpt de ejemplo para crear una imagen de un sistema de archivos.
#@brief   Se usa como base para el programa de creación de imágenes de OpenGnsys Admin).
#@param 1 disco 
#@param 2 particion 
#@param 3 REPO|CACHE
#@param 4 imagen
#@return  
#@exception OG_ERR_FORMAT     # 1 formato incorrecto.
#@exception OG_ERR_PARTITION  # 3 Error en partición de disco o en su sistema de archivos
#@exception OG_ERR_IMAGE      # 5 Error en funcion ogCreateImage o ogRestoreImage.
#@exception OG_ERR_NOTWRITE   # 14 error de escritura
#@exception OG_ERR_NOTCACHE   # 15 si cache no existe 15
#@exception OG_ERR_CACHESIZE  # 16 si espacio de la cache local o remota no tiene espacio 16
#@exception OG_ERR_REDUCEFS   # 17 error al reducir sistema de archivos.
#@exception OG_ERR_EXTENDFS   # 18 Errror al expandir el sistema de archivos.
#@note   
#@todo: que hacer, si el tamaño de la cache es sufciente, pero no tiene espacio libre
#@todo: que hacer, si hay una imagen con igual nombre en la cache
#@version 1.0 - control de errores para el ogAdmServer
#@author  
#@date   2011-04-10
#@version 1.0.1 - Control de espacio requerido
#@author  Antonio J.Doblas Viso
#@date   2011-05-10
#@version 1.0.2 - Separacion de log
#@author  Antonio J.Doblas Viso
#@date   2011-08-4
#@version 1.1.0 - La copia de seguridad de la imagen antigua se hace después de las comprobaciones.
#@author  Irina Gomez - ETSII Universidad de Sevilla
#@date    2016-10-14
#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771)
#@author  Irina Gomez - ETSII Universidad de Sevilla
#@date    2017-03-28
#@version 1.1.1 - #802 Equipos EFI: se guarda el cargador de arranque y UUID de las particiones
#@author  Irina Gomez - ETSII Universidad de Sevilla
#@date    2019-01-08
#*/ ##

# Test 1.  crear una imagen en un REPO sin espacio libre. 
# test 2.  crear una imagen en un REPO en modo solo lectura.
# test 3.  intentar crear una imagen en la cache de un equipo que no la disponga.
# test 4.  crear una imagen en la Cache sin espacio sufiente. 
# test 5.  intentar crear una imagen, en la que no se puede reducir el FS.


PROG="$(basename $0)"
if [ $# -ne 4 ]; then
    ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE imagen"
    exit $?
fi

TIME1=$SECONDS

#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg

# Valores por defecto en etc/engine.cfg
#IMGPROG="partclone"
#IMGCOMP="lzop"
IMGEXT=${IMGEXT:-"img"}
#IMGREDUCE="TRUE"
REPO="${3^^}"

# Unidad organizativa
[ "$ogunit" != "" ] && OGUNIT="$ogunit"

# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
# salvo si es llamado desde createImageCustom
if [ "$(ogGetCaller)" != "createImageCustom" ]; then
    echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp
fi

ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"

# Si es una ip y es igual a la del equipo restaura desde cache
[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE"
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
ogCheckIpAddress $REPO
if [ $? == 0 -o $REPO == "REPO" ] ; then
        # Si falla el cambio -> salimos con error repositorio no valido
        ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?)
        REPO="REPO"
fi

# Si el repositorio es CACHE comprobamos que exista
if [ "$REPO" == "CACHE" ]; then 
    ! ogFindCache >/dev/null && exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?)
fi

# Obtener información de los parámetros de entrada.
PART=$(ogDiskToDev "$1" "$2" 2>/dev/null) || exit $(ogRaiseError $OG_ERR_PARTITION "$1 $2"; echo $?)

#Comprobamos acceso de escritura.
DIRTEMP=$(date +%Y%m%d-%H%M%S)
ogMakeDir $REPO /$4$DIRTEMP 2>/dev/null || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO"; echo $?) && ogDeleteTree $REPO /$4$DIRTEMP 

IMGDIR=$(ogGetParentPath "$REPO" "/$4")
# Si no existe, crear subdirectorio de la imagen.
if [ $? != 0 ]; then
    ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$REPO $(dirname "$4")."
    ogMakeDir "$REPO" $(dirname "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?)
    IMGDIR=$(ogGetParentPath "$REPO" "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?)
fi
IMGFILE=$IMGDIR/$(basename "/$4").$IMGEXT

echo " " > $OGLOGCOMMAND
# Borramos ficheros de paginacion y configuracion
ogCleanOs $1 $2

#Comprobar espacio que requerira la imagen para ser almacenada
read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$REPO" "$4")

ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE"
[ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$REPO"; echo $?)

# Comprobar consistencia del sistema de archivos.
echo " " > $OGLOGCOMMAND
SIZEFS=$(ogGetFsSize  $1 $2)
ogEcho log session "[20] $MSG_HELP_ogCheckFs  $PART $SIZEFS (KB)"
ogUnmount $1 $2 2>/dev/null
ogCheckFs $1 $2 || exit $(ogRaiseError $OG_ERR_PARTITION "ogCheckFs $1 $2" && echo $?)

# Si es UEFI copio el cargador de arranque a la partición
OSTYPE="$(ogGetOsType $1 $2)"
if ogIsEfiActive && [ "$OSTYPE" == "Windows" ]; then
    ogEcho log session "[25] $MSG_HELP_ogCopyEfiBootLoader" 
    ogCopyEfiBootLoader $1 $2
fi

# Evaluar variable de engine.cfg para reducir el sistema de archivos en la creacion
if [ "$IMGREDUCE" == "TRUE" ]
then 
    ogEcho log session "[30] $MSG_HELP_ogReduceFs"
    ogReduceFs $1 $2 &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_REDUCEFS "$1 $2"; echo $?)
    NEWSIZEFS=$(ogGetFsSize  $1 $2)
    TIMEAUX=$[SECONDS-TIME1]
    ogEcho log session "      $MSG_SCRIPTS_TIME_PARTIAL ( $NEWSIZEFS KB ) : $[TIMEAUX/60]m $[TIMEAUX%60]s"
fi

# Renombrar el fichero de imagen si ya existe.
if [ -f "$IMGFILE" ]; then
    ogEcho log session "[35] $MSG_SCRIPTS_FILE_RENAME \"$IMGFILE\" ->  \"$IMGFILE.ant\"."
    mv "$IMGFILE" "$IMGFILE.ant"
    mv "$IMGFILE.torrent" "$IMGFILE.torrent.ant" 2>/dev/null
    mv "$IMGFILE.sum" "$IMGFILE.sum.ant" 2>/dev/null
    mv "$IMGFILE.full.sum" "$IMGFILE.full.sum.ant" 2>/dev/null
fi

# Crear la imagen.
echo " " > $OGLOGCOMMAND
TIME2=$SECONDS
ogEcho log session "[40] $MSG_HELP_ogCreateImage : ogCreateImage $1 $2 $REPO $4 $IMGPROG $IMGCOMP"
ogCreateImage "$1" "$2" "$REPO" "/$4" "$IMGPROG" "$IMGCOMP" &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_IMAGE "ogCreteImage"; echo $?)
RESUMECREATEIMAGE=$(grep "Total Time:" $OGLOGCOMMAND)
TIMEAUX2=$[SECONDS-TIME2]
ogEcho log session "      $RESUMECREATEIMAGE "
ogEcho log session "      $MSG_SCRIPTS_TIME_PARTIAL : $[TIMEAUX2/60]m $[TIMEAUX2%60]s"

# Extender sistema de archivos
TIME3=$SECONDS
ogEcho log session "[90] Extender sistema de archivos."
ogExtendFs $1 $2 || exit $(ogRaiseError $OG_ERR_EXTENDFS "$1 $2"; echo $?)
SIZEFS2=$(ogGetFsSize  $1 $2)
TIMEAUX3=$[SECONDS-TIME3]
ogEcho log session "      $MSG_HELP_ogExtendFs  $NEWSIZEFS ->  $SIZEFS = $SIZEFS2: $[TIMEAUX3/60]m $[TIMEAUX3%60]s"

#TODO que hacer si error al extender sistemade archivos

#resumen de la operacion
IMGSIZE=$(ls -s `ogGetPath $REPO /$4.$IMGEXT`| cut -f1 -d" ")
IMGOS=$(ogGetImageInfo `ogGetPath $REPO /$4.$IMGEXT`)

TIME=$[SECONDS-TIME1]
ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s"
ogEcho log session "      FileSystem $PART with $NEWSIZEFS KB data created onto file-image as $4 and used $IMGSIZE KB across DFS $ogprotocol"
ogEcho log session "      Image-file $4 metada: $IMGOS"
