source: client/engine/Image.lib @ b444fa7

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since b444fa7 was 5827bb9, checked in by ramon <ramongomez@…>, 8 years ago

#726 #740: Compatibilidad para restaurar con antiguas versiones de partclone y reducir errores de funciones og...Syntax.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5303 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 36.1 KB
RevLine 
[715bedc]1#!/bin/bash
2#/**
3#@file    Image.lib
4#@brief   Librería o clase Image
5#@class   Image
6#@brief   Funciones para creación, restauración y clonación de imágenes de sistemas.
[e39921b]7#@version 1.1.0
[715bedc]8#@warning License: GNU GPLv3+
9#*/
10
[914d834]11
[e39921b]12#/**
[2fc81c4]13#         ogCreateImageSyntax path_device path_filename [str_tool] [str_compressionlevel]
[914d834]14#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
[bbe1bcf]15#@param   path_device           dispositivo Linux del sistema de archivos
[2fc81c4]16#@param   path_fileneme         path absoluto del fichero imagen
[bbe1bcf]17#@param   [opcional] str_tool   herrmaienta de clonacion [partimage, partclone, ntfsclone]
18#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
19#@return  str_command - cadena con el comando que se debe ejecutar.
20#@warning Salida nula si se producen errores.
[914d834]21#@TODO    introducir las herramientas fsarchiver, dd
22#@version 1.0 - Primeras pruebas
23#@author  Antonio J. Doblas Viso. Universidad de Málaga
24#@date    2010/02/08
[bbe1bcf]25#@version 1.0.5 - Incrustar códico de antigua función ogPartcloneSyntax
26#@author  Ramon Gomez, ETSII Universidad de Sevilla
27#@date    2012/09/14
[914d834]28#*/ ##
29function ogCreateImageSyntax()
30{
[1feb465]31local FS TOOL LEVEL DEV IMGFILE BUFFER PARAM1 PARAM2 PARAM3
[914d834]32
33# Si se solicita, mostrar ayuda.
34if [ "$*" == "help" ]; then
[bbe1bcf]35    ogHelp "$FUNCNAME" "$FUNCNAME path_device path_imagefile [str_tool] [str_compressionlevel]" \
36           "$FUNCNAME /dev/sda1 /opt/opengnsys/images/prueba.img partclone lzop" \
37           "$FUNCNAME /dev/sda1 /opt/opengnsys/images/prueba.img"
[914d834]38    return
39fi
[2fc81c4]40# Error si no se reciben entre 2 y 4 parámetros.
41[ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[914d834]42
[2fc81c4]43# Asignación de parámetros.
[1feb465]44DEV="$1"
[bbe1bcf]45IMGFILE="$2"
[914d834]46case "$#" in
[1feb465]47    2)  # Sintaxis por defecto OG DEV IMGFILE
[bbe1bcf]48        TOOL="partclone"
49        LEVEL="gzip"
50        ;;
51    4)  # Sintaxis condicionada.
52        TOOL="${3,,}"
53        LEVEL="${4,,}"
54        ;;
55esac
[914d834]56
[bbe1bcf]57case "$TOOL" in
58    ntfsclone)
[1feb465]59        PARAM1="ntfsclone --force --save-image -O - $DEV"
[bbe1bcf]60        ;;
61    partimage|default)
[1feb465]62        PARAM1="partimage -M -f3 -o -d -B gui=no -c -z0 --volume=0 save $DEV stdout"
[bbe1bcf]63        ;;
64    partclone)
[1feb465]65        FS="$(ogGetFsType $(ogDevToDisk $DEV 2>/dev/null) 2>/dev/null)"
[bbe1bcf]66        case "$FS" in
67            EXT[234]) PARAM1="partclone.extfs" ;;
68            BTRFS)    PARAM1="partclone.btrfs" ;;
69            REISERFS) PARAM1="partclone.reiserfs" ;;
70            REISER4)  PARAM1="partclone.reiser4" ;;
71            JFS)      PARAM1="partclone.jfs" ;;
72            XFS)      PARAM1="partclone.xfs" ;;
[48c9e6e]73            F2FS)     PARAM1="partclone.f2fs" ;;
74            NILFS2)   PARAM1="partclone.nilfs2" ;;
[bbe1bcf]75            NTFS)     PARAM1="partclone.ntfs" ;;
[9836a86]76            EXFAT)    PARAM1="partclone.exfat" ;;
[bbe1bcf]77            FAT16|FAT32) PARAM1="partclone.fat" ;;
78            HFS|HFSPLUS) PARAM1="partclone.hfsp" ;;
[9836a86]79            UFS)      PARAM1="partclone.ufs" ;;
[48c9e6e]80            VMFS)     PARAM1="partclone.vmfs" ;;
81            *)        PARAM1="partclone.imager" ;;
[bbe1bcf]82        esac
[9836a86]83        # Por compatibilidad, si no existe el ejecutable usar por defecto "parclone.dd".
84        which $PARAM1 &>/dev/null || PARAM1="partclone.dd"
[1feb465]85        PARAM1="$PARAM1 -d0 -F -c -s $DEV"
[a4c4374]86        # Algunas versiones de partclone.dd no tienen opción "-c".
87        [ -z "$(eval ${PARAM1%% *} --help 2>&1 | grep -- -c)" ] && PARAM1="${PARAM1/ -c / }"
[1feb465]88        ;;
89esac
90# Comprobar que existe mbuffer.
[9836a86]91which mbuffer &>/dev/null && PARAM2="| mbuffer -q -m 40M " || PARAM2=" "
[bbe1bcf]92
93# Nivel de compresion.
94case "$LEVEL" in
95    0|none) PARAM3=" > " ;;
96    1|lzop) PARAM3=" | lzop > " ;;
97    2|gzip) PARAM3=" | gzip -c > " ;;
98    3|bzip) PARAM3=" | bzip -c > " ;;
[914d834]99esac
[bbe1bcf]100
101# Sintaxis final.
102[ -n "$PARAM1" ] && echo "$PARAM1 $PARAM2 $PARAM3 $IMGFILE"
[914d834]103}
104
105
106#/**
[2fc81c4]107#         ogRestoreImageSyntax path_filename path_device [str_tools] [str_compressionlevel]
[914d834]108#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
[2fc81c4]109#@param   path_device           dispositivo Linux del sistema de archivos
110#@param   path_fileneme         path absoluto del fichero imagen
111#@param   [opcional] str_tools  herrmaienta de clonacion [partimage, partclone, ntfsclone]
112#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
[914d834]113#@return  cadena con el comando que se debe ejecutar.
114#@exception OG_ERR_FORMAT    formato incorrecto.
115#@warning En pruebas iniciales
116#@TODO    introducir las herramientas fsarchiver, dd
117#@TODO    introducir el nivel de compresion gzip
118#@version 1.0 - Primeras pruebas
119#@author  Antonio J. Doblas Viso. Universidad de Málaga
120#@date    2010/02/08
121#*/ ##
[46a1ff9]122function ogRestoreImageSyntax ()
[914d834]123{
124local TOOL COMPRESSOR LEVEL PART IMGFILE FILEHEAD INFOIMG
125
126
127# Si se solicita, mostrar ayuda.
128if [ "$*" == "help" ]; then
129    ogHelp "$FUNCNAME" "$FUNCNAME  filename partition [tool] [levelcompresor]" \
130           "$FUNCNAME  /opt/opengnsys/images/prueba.img /dev/sda1 [partclone] [lzop]"
131    return
132fi
133
[2fc81c4]134# Error si no se reciben entre 2 y 4 parámetros.
135[ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[914d834]136
137# controlamos que el parametro 1 (imagen) es tipo file.
138[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
139
140# Si 2 parametros (file-origen-, device-destino-) = ogGetImageFull($1)
141if [ "$#" -eq 2 ]; then
142        IMGFILE=$1
143        PART=$2
144        INFOIMG=$(ogGetImageInfo $IMGFILE) || ogRaiseError $OG_ERR_NOTFOUND "No Image $1" || return $?
145        TOOL=`echo $INFOIMG | cut -f1 -d:`
146        COMPRESSOR=`echo $INFOIMG | cut -f2 -d:`
147        ogRestoreImageSyntax $IMGFILE $PART $TOOL $COMPRESSOR
148fi
149
150
151# Si cuatro parametros genera sintaxis
152if [ "$#" -eq 4 ]; then
153        IMGFILE=$1
154        PART=$2
155        # comprobamos parametro herramienta compresion.
156        TOOL=$(echo $3 | tr [A-Z] [a-z])       
157        #ogCheckProgram $TOOL
158        #comprobar parámetro compresor.
159        LEVEL=$(echo $4 | tr [A-Z] [a-z])
160        #ogCheckProgram $LEVEL
161       
162        case "$LEVEL" in
163        "0"|"none")
164                COMPRESSOR=" "
165        ;;
166        "1"|"lzop" | "LZOP")
167                COMPRESSOR=" lzop -dc "
168        ;;
169        "2"|"gzip" | "GZIP")
170                COMPRESSOR=" gzip -dc "
171        ;;
172        "3"|"bzip" | "BZIP" )
173                COMPRESSOR=" bzip -dc "
174        ;;
175        *)
176                ogRaiseError $OG_ERR_NOTFOUND "Compressor no valid $TOOL" || return $?
177        ;;
178        esac
179    #comprobar mbuffer
180        which mbuffer > /dev/null && MBUFFER="| mbuffer -q -m 40M " || MBUFFER=" "
181
[5827bb9]182        case "${TOOL,,}" in
183                ntfsclone)
[914d834]184                        TOOL="| ntfsclone --restore-image --overwrite $PART -"
185                ;;
[5827bb9]186                partimage)
[914d834]187                        TOOL="| partimage -f3 -B gui=no restore $PART stdin"
188                ;;
[5827bb9]189                partclone*)
[914d834]190                    # -C para que no compruebe tamaños
[0084b42]191                        TOOL="| partclone.restore -d0 -C -I -o $PART"
[914d834]192                ;;
[5827bb9]193                dd)
[1feb465]194                        TOOL="| pv | dd conv=sync,noerror bs=1M of=$PART"
195                ;;
[914d834]196                *)
197                ogRaiseError $OG_ERR_NOTFOUND "Tools imaging no valid $TOOL" || return $?
198        ;;
199        esac
200
201        echo "$COMPRESSOR $IMGFILE $MBUFFER $TOOL"
202fi
203
204}
205
206
207
[715bedc]208
209#/**
[1c9ef24]210#         ogCreateDiskImage int_ndisk str_repo path_image [str_tools] [str_compressionlevel]
211#@brief   Crea una imagen (copia de seguridad) de un disco completo.
212#@param   int_ndisk      nº de orden del disco
213#@param   str_repo       repositorio de imágenes (remoto o caché local)
214#@param   path_image     camino de la imagen (sin extensión)
215#@return  (nada, por determinar)
216#@note    repo = { REPO, CACHE }
217#@note    Esta primera versión crea imágenes con dd comprimidas con gzip.
218#@exception OG_ERR_FORMAT    formato incorrecto.
219#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
220#@exception OG_ERR_LOCKED    particion bloqueada por otra operación.
221#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
222#@warning En pruebas iniciales
223#@todo    Gestión de bloqueos de disco
224#@todo    Comprobar si debe desmontarse la caché local
225#@todo    Comprobar que no se crea la imagen en el propio disco
226#@version 1.1.0 -  Primera versión para OpenGnsys con herramientas prefijadas.
227#@author  Ramon Gomez, ETSII Universidad de Sevilla
228#@Date    2016/04/08
229#*/ ##
230function ogCreateDiskImage ()
231{
232# Variables locales
233local DISK PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE
234
235# Si se solicita, mostrar ayuda.
236if [ "$*" == "help" ]; then
237    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
238           "$FUNCNAME 1 REPO /disk1"
239    return
240fi
241# Error si no se reciben entre 3 y 5 parámetros.
242[ $# -ge 3 -a $# -le 5 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
243
244# Comprobar que no está bloqueada ni la partición, ni la imagen.
245DISK="$(ogDiskToDev $1)" || return $?
[a30ad15f]246if ogIsDiskLocked $1; then
[1c9ef24]247    ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1"
248    return $?
249fi
250IMGTYPE="dsk"                   # Extensión genérica de imágenes de disco.
251IMGDIR=$(ogGetParentPath "$2" "$3")
252[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
253IMGFILE="$IMGDIR/$(basename "$3").$IMGTYPE"
254if ogIsImageLocked "$IMGFILE"; then
255    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4"
256    return $?
257fi
[bac2d63]258
259# No guardar imagen en el propio disco (disco no incluido en el camino del repositorio).
260if [[ $(ogGetPath "$2" /) =~ ^$DISK ]]; then
261    ogRaiseError $OG_ERR_IMAGE "$2 = $DISK"
262    return $?
263fi
264
[1c9ef24]265# Generar la instruccion a ejecutar antes de aplicar los bloqueos.
[46a1ff9]266PROGRAM=$(ogCreateImageSyntax $DISK $IMGFILE)
[bac2d63]267# Desmontar todos los sistemas de archivos del disco, bloquear disco e imagen.
[1c9ef24]268ogUnmountAll $1 2>/dev/null
269ogLockDisk $1 || return $?
270ogLockImage "$2" "$3.$IMGTYPE" || return $?
271
272# Crear Imagen.
273trap "ogUnlockDisk $1; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9
274eval $PROGRAM
275
276# Controlar salida de error y desbloquear partición.
277ERRCODE=$?
278if [ $ERRCODE != 0 ]; then
279    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
280    rm -f "$IMGFILE"
281fi
[bac2d63]282# Desbloquear disco e imagen.
[1c9ef24]283ogUnlockDisk $1
284ogUnlockImage "$2" "$3.$IMGTYPE"
285return $ERRCODE
286}
287
288
289
290#/**
[2fc81c4]291#         ogCreateImage int_ndisk int_npartition str_repo path_image [str_tools] [str_compressionlevel]
[715bedc]292#@brief   Crea una imagen a partir de una partición.
[42669ebf]293#@param   int_ndisk      nº de orden del disco
294#@param   int_npartition nº de orden de la partición
295#@param   str_repo       repositorio de imágenes (remoto o caché local)
296#@param   path_image     camino de la imagen (sin extensión)
[2fc81c4]297#@param   [opcional] str_tools  herrmaienta de clonacion [partimage, partclone, ntfsclone]
298#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
[715bedc]299#@return  (nada, por determinar)
[ebf06c7]300#@note    repo = { REPO, CACHE }
[cfeabbf]301#@exception OG_ERR_FORMAT    formato incorrecto.
302#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
303#@exception OG_ERR_PARTITION partición no accesible o no soportada.
304#@exception OG_ERR_LOCKED    particion bloqueada por otra operación.
305#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
[3458879]306#@todo    Comprobaciones, control de errores, definir parámetros, etc.
[985bef0]307#@version 0.1 -  Integracion para Opengnsys  -  HIDRA:CrearImagen{EXT3, NTFS}.sh;  EAC: CreateImageFromPartition () en Deploy.lib
[bbe1bcf]308#@author  Ramon Gomez, ETSII Universidad de Sevilla
[985bef0]309#@Date    2008/05/13
310#@author  Antonio J. Doblas Viso. Universidad de Malaga
311#@date    2008/10/27
[0fbc05e]312#@version 0.9 - Versión en pruebas para OpenGnSys
[715bedc]313#@author  Ramon Gomez, ETSII Universidad de Sevilla
[cfeabbf]314#@date    2009/10/07
[bbe1bcf]315#@version 1.0 - Llama a función ogCreateImageSyntax para generar la llamada al comando.
316#@author  Antonio J. Doblas Viso. Universidad de Málaga
317#@date    2010/02/08
[1e7eaab]318#*/ ##
[42669ebf]319function ogCreateImage ()
320{
[59f9ad2]321# Variables locales
[08b941f]322local PART PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE
[59f9ad2]323
[42669ebf]324# Si se solicita, mostrar ayuda.
[59f9ad2]325if [ "$*" == "help" ]; then
326    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart path_dir str_image" \
[3543b3e]327           "$FUNCNAME 1 1 REPO /aula1/winxp"
[59f9ad2]328    return
329fi
[2fc81c4]330# Error si no se reciben entre 4 y 6 parámetros.
331[ $# -ge 4 -a $# -le 6 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[59f9ad2]332
[08b941f]333# Comprobar que no está bloqueada ni la partición, ni la imagen.
[715bedc]334PART="$(ogDiskToDev $1 $2)" || return $?
[a79dd508]335if ogIsLocked $1 $2; then
[e39921b]336    ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1, $2"
[a79dd508]337    return $?
338fi
[a73649d]339
[914d834]340IMGTYPE="img"                   # Extensión genérica de imágenes.
[cfeabbf]341IMGDIR=$(ogGetParentPath "$3" "$4")
342[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$3 $(dirname $4)" || return $?
[a73649d]343
[08b941f]344IMGFILE="$IMGDIR/$(basename "$4").$IMGTYPE"
345if ogIsImageLocked "$IMGFILE"; then
346    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4"
347    return $?
348fi
[bbe1bcf]349# Generar la instruccion a ejecutar antes de aplicar los bloqueos.
350PROGRAM=$(ogCreateImageSyntax $PART $IMGFILE $5 $6)
[08b941f]351# Desmontar partición, bloquear partición e imagen.
[cfeabbf]352ogUnmount $1 $2 2>/dev/null
[a79dd508]353ogLock $1 $2 || return $?
[08b941f]354ogLockImage "$3" "$4.$IMGTYPE" || return $?
[715bedc]355
[08b941f]356# Crear Imagen.
357trap "ogUnlock $1 $2; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9
[914d834]358eval $PROGRAM
[08b941f]359
[42669ebf]360# Controlar salida de error y desbloquear partición.
[cfeabbf]361ERRCODE=$?
[f5432db7]362if [ $ERRCODE != 0 ]; then
[cfeabbf]363    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
[f5432db7]364    rm -f "$IMGFILE"
[cfeabbf]365fi
[08b941f]366# Desbloquear partición e imagen.
[715bedc]367ogUnlock $1 $2
[08b941f]368ogUnlockImage "$3" "$4.$IMGTYPE"
[cfeabbf]369return $ERRCODE
[715bedc]370}
371
[b094c59]372
[a25cc03]373#/**
374#         ogCreateMbrImage int_ndisk str_repo path_image
375#@brief   Crea una imagen a partir del sector de arranque de un disco.
376#@param   int_ndisk    nº de orden del disco
377#@param   str_repo     repositorio de imágenes (remoto o caché local)
378#@param   path_image   camino de la imagen (sin extensión)
379#@return  (nada, por determinar)
380#@note    repo = { REPO, CACHE }
381#@exception OG_ERR_FORMAT    formato incorrecto.
382#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
383#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
384#@version 0.9 - Versión en pruebas para OpenGNSys
385#@author  Ramon Gomez, ETSII Universidad de Sevilla
386#@date    2010/01/12
387#@version 1.0 - Adaptación a OpenGnSys 1.0
388#@author  Ramon Gomez, ETSII Universidad de Sevilla
389#@date    2011/03/10
390#*/ ##
391function ogCreateMbrImage ()
392{
393# Variables locales
394local DISK IMGDIR IMGFILE
395# Si se solicita, mostrar ayuda.
396if [ "$*" == "help" ]; then
397    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
398           "$FUNCNAME 1 REPO /aula1/mbr"
399    return
400fi
401# Error si no se reciben 3 parámetros.
[a73649d]402[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]403
404DISK=$(ogDiskToDev "$1") || return $?
405IMGDIR=$(ogGetParentPath "$2" "$3")
406[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
407IMGFILE="$IMGDIR/$(basename "$3").mbr"
408
409# Crear imagen del MBR.
410dd if="$DISK" of="$IMGFILE" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
411}
412
413
414#/**
[b52e658]415#         ogCreateBootLoaderImage int_ndisk str_repo path_image
416#@brief   Crea una imagen del boot loader a partir del sector de arranque de un disco.
417#@param   int_ndisk    nº de orden del disco
418#@param   str_repo     repositorio de imágenes (remoto o caché local)
419#@param   path_image   camino de la imagen (sin extensión)
420#@return  (nada, por determinar)
421#@note    repo = { REPO, CACHE }
422#@exception OG_ERR_FORMAT    formato incorrecto.
423#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
424#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
425#@version 1.0 - Adaptacion de ogCreateMbrImage para guardar solo el Boot Loader
426#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
427#@date    2011/03/21
428#*/ ##
429function ogCreateBootLoaderImage ()
430{
431# Variables locales
432local DISK IMGDIR IMGFILE
433# Si se solicita, mostrar ayuda.
434if [ "$*" == "help" ]; then
435    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
436           "$FUNCNAME 1 REPO /aula1/mbr"
437    return
438fi
439# Error si no se reciben 3 parámetros.
[a73649d]440[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]441
442DISK=$(ogDiskToDev "$1") || return $?
443IMGDIR=$(ogGetParentPath "$2" "$3")
444[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
445IMGFILE="$IMGDIR/$(basename "$3").mbr"
446
447# Crear imagen del Boot Loader dentro del MBR.
448dd if="$DISK" of="$IMGFILE" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
449}
450
[d3dc88d]451#/**
452#         ogGetSizeParameters int_num_disk  int_num_part str_repo [monolit|sync|diff]
453#@brief   Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido.
454#@param   int_disk     numero de disco
455#@param   int_part     numero de particion
456#@param   str_repo     repositorio de imágenes   { REPO, CACHE }
457#@param   str_imageType Tipo de imagen: monolit (por defecto), sync o diff. (parametro opcional)
[e784187]458#@return  SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE
[d3dc88d]459#@note    si str_imageType= diff necesario /tmp/ogimg.info, que es creado por ogCreateInfoImage.
460#@exception OG_ERR_FORMAT    formato incorrecto.
461#@author  Irina Gomez, ETSII Universidad de Sevilla
462#@date    2014/10/24
[e784187]463#@version 1.1.0 - En la salida se incluye el espacio disponible en el repositorio (ticket #771)
464#@author  Irina Gomez - ETSII Universidad de Sevilla
465#@date    2017-03-28
[d3dc88d]466#*/ ##
467function ogGetSizeParameters ()
468{
469local MNTDIR SIZEDATA KERNELVERSION SIZEREQUIRED FACTORGZIP FACTORLZOP SIZEFREE
470# Si se solicita, mostrar ayuda.
471if [ "$*" == "help" ]; then
472    ogHelp "$FUNCNAME" "$FUNCNAME num_disk num_part str_repo [monolic|sync|diff]" \
473           "if $FUNCNAME 1 2 REPO sync ; then ...; fi" \
474           "if $FUNCNAME 1 6 CACHE ; then ...; fi"
475    return
476fi
477# Error si no se reciben 1 o 2 parámetros.
478[ $# -lt 3 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE [monolitic|sync]" ; echo $?)
479
480MNTDIR=$(ogMount $1 $2)
481if [ "$MNTDIR" == "" ]; then
482    ogRaiseError $OG_ERR_PARTITION "$1 $2"
483    return $?
484fi
485
486# Datos contenidos en la particion o en la lista de archivos de contiene la diferencial.
487if [ "_${4^^}_" == "_DIFF_" ]; then
488        [ -r /tmp/ogimg.info ] || return $(ogRaiseError session $OG_ERR_NOTFOUND "/tmp/ogimg.info"; echo $?)
489        cd $MNTDIR
490        SIZEDATA=$(grep -v "\/$" /tmp/ogimg.info | tr '\n' '\0'| du -x -c --files0-from=- 2>/dev/null|tail -n1 |cut -f1)
491else
492        SIZEDATA=$(df -k | grep $MNTDIR | awk '{print $3}')
493fi
494
495#Aplicar factor de compresion
496if [ "_${4^^}_" == "_SYNC_" -o "_${4^^}_" == "_DIFF_" ]; then
497       
498        # Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision
499        KERNELVERSION=$(uname -r| awk '{printf("%d",$1);sub(/[0-9]*\./,"",$1);printf(".%02d",$1)}')
500        [ $KERNELVERSION \< 3.07 ] &&  IMGFS="EXT4" || IMGFS=${IMGFS:-"BTRFS"}
501        FACTORSYNC=${FACTORSYNC:-"120"}
502        # Si IMGFS="BTRFS" la compresion es mayor.
[81ae95c]503        [ $IMGFS == "BTRFS" ] && let FACTORSYNC=$FACTORSYNC-20
[d3dc88d]504
505        let SIZEREQUIRED=$SIZEDATA*$FACTORSYNC/100
506        # El tamaño mínimo del sistema de ficheros btrfs es 250M, ponemos 300
507        [ $SIZEREQUIRED -lt 300000 ] && SIZEREQUIRED=300000
508       
509else
510        FACTORGZIP=55/100
511        FACTORLZOP=65/100
512        let SIZEREQUIRED=$SIZEDATA*$FACTORLZOP
513fi
514
515#Comprobar espacio libre en el contenedor.
516[ "${3^^}" == "CACHE" ] && SIZEFREE=$(ogGetFreeSize `ogFindCache`)
517[ "${3^^}" == "REPO" ] && SIZEFREE=$(df -k | grep $OGIMG | awk '{print $4}')
518
519[ "$SIZEREQUIRED" -lt "$SIZEFREE" ] && ISENOUGHSPACE=TRUE  ||  ISENOUGHSPACE=FALSE
520
[e784187]521echo $SIZEDATA $SIZEREQUIRED $SIZEFREE $ISENOUGHSPACE
[d3dc88d]522
523
524}
[cbbb046]525
[b52e658]526#/**
[a25cc03]527#         ogIsImageLocked [str_repo] path_image
528#@brief   Comprueba si una imagen está bloqueada para uso exclusivo.
529#@param   str_repo     repositorio de imágenes (opcional)
530#@param   path_image   camino de la imagen (sin extensión)
[7685100]531#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
[a25cc03]532#@note    repo = { REPO, CACHE }
533#@exception OG_ERR_FORMAT    formato incorrecto.
534#@version 1.0 - Adaptación a OpenGnSys 1.0
535#@author  Ramon Gomez, ETSII Universidad de Sevilla
536#@date    2011/03/10
[7685100]537#@version 1.0.1 - Devolver falso en caso de error.
538#@author  Ramon Gomez, ETSII Universidad de Sevilla
539#@date    2011-05-18
[a25cc03]540#*/ ##
541function ogIsImageLocked ()
542{
543# Si se solicita, mostrar ayuda.
544if [ "$*" == "help" ]; then
545    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
546           "if $FUNCNAME /opt/opengnsys/images/aula1/winxp.img; then ...; fi" \
547           "if $FUNCNAME REPO /aula1/winxp.img; then ...; fi"
548    return
549fi
550# Error si no se reciben 1 o 2 parámetros.
[7685100]551[ $# -lt 1 -o $# -gt 2 ] && return 1
[914d834]552
[a25cc03]553# Comprobar si existe el fichero de bloqueo.
554test -n "$(ogGetPath $@.lock)"
555}
[914d834]556
557
[a25cc03]558#/**
559#         ogLockImage [str_repo] path_image
560#@brief   Bloquea una imagen para uso exclusivo.
561#@param   str_repo     repositorio de imágenes (opcional)
562#@param   path_image   camino de la imagen (sin extensión)
563#@return  Nada.
564#@note    Se genera un fichero con extensión .lock
565#@note    repo = { REPO, CACHE }
566#@exception OG_ERR_FORMAT    formato incorrecto.
567#@version 1.0 - Adaptación a OpenGnSys 1.0
568#@author  Ramon Gomez, ETSII Universidad de Sevilla
569#@date    2011/03/10
570#*/ ##
571function ogLockImage ()
572{
573# Variables locales
574local IMGDIR
[914d834]575
[a25cc03]576# Si se solicita, mostrar ayuda.
577if [ "$*" == "help" ]; then
578    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
579           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
580           "$FUNCNAME REPO /aula1/winxp.img"
581    return
582fi
583# Error si no se reciben 1 o 2 parámetros.
[a73649d]584[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]585# Comprobar que existe directorio de imagen
586IMGDIR=$(ogGetParentPath $@) || return $?
587# Crear fichero de bloqueo.
[a73649d]588touch $IMGDIR/$(basename "${!#}").lock 2>/dev/null || ogRaiseError $OG_ERR_NOTWRITE "$*" || return $?
[a25cc03]589}
[914d834]590
591
592#/**
[e39921b]593#         ogRestoreDiskImage str_repo path_image int_npartition
594#@brief   Restaura (recupera) una imagen de un disco completo.
595#@param   str_repo       repositorio de imágenes o caché local
596#@param   path_image     camino de la imagen
597#@param   int_ndisk      nº de orden del disco
598#@return  (por determinar)
599#@warning Primera versión en pruebas
600#@todo    Gestionar bloqueos de disco
601#@todo    Comprobar que no se intenta restaurar de la caché sobre el mismo disco
602#@exception OG_ERR_FORMAT    formato incorrecto.
603#@exception OG_ERR_NOTFOUND  fichero de imagen o partición no detectados.
604#@exception OG_ERR_LOCKED    partición bloqueada por otra operación.
605#@exception OG_ERR_IMAGE     error al restaurar la imagen del sistema.
606#@exception OG_ERR_IMGSIZEPARTITION  Tamaño de la particion es menor al tamaño de la imagen.
607#@version 1.1.0 - Primera versión para OpenGnsys.
608#@author Ramon Gomez, ETSII Universidad de Sevilla
[1c9ef24]609#@Date    2016/04/08
[e39921b]610#*/ ##
611function ogRestoreDiskImage ()
612{
613# Variables locales
614local DISK DISKSIZE IMGFILE IMGTYPE IMGSIZE PROGRAM ERRCODE
615
616# Si se solicita, mostrar ayuda.
617if [ "$*" == "help" ]; then
618    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
619           "$FUNCNAME REPO /aula1/winxp 1"
620    return
621fi
622# Error si no se reciben 4 parámetros.
623[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
624# Procesar parámetros.
625DISK="$(ogDiskToDev $3)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
626IMGTYPE="dsk"
627IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
628[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
629
630# comprobamos consistencia de la imagen
[1c9ef24]631ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[e39921b]632# Error si la imagen no cabe en la particion.
633#IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
634#DISKSIZE=$(ogGetDiskSize $3)
635#if [ $IMGSIZE -gt $DISKSIZE ]; then
636#    ogRaiseError $OG_ERR_IMGSIZEPARTITION "$DISKSIZE < $IMGSIZE"
637#    return $?
638#fi
639# Comprobar el bloqueo de la imagen y de la partición.
640if ogIsImageLocked "$IMGFILE"; then
641    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
642    return $?
[1feb465]643fi
[c680f93]644if ogIsDiskLocked $3; then
645    ogRaiseError $OG_ERR_LOCKED "$MSG_DISK $3"
646    return $?
647fi
[e39921b]648# Solicitamos la generación de la instruccion a ejecutar
[1feb465]649PROGRAM=$(ogRestoreImageSyntax $IMGFILE $DISK)
[e39921b]650
651# Bloquear el disco
[1c9ef24]652ogLockDisk $3 || return $?
653trap "ogUnlockDisk $3" 1 2 3 6 9
[e39921b]654
655# Ejecutar restauración según el tipo de imagen.
656eval $PROGRAM
657
658ERRCODE=$?
659if [ $ERRCODE != 0 ]; then
660    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
661fi
[1c9ef24]662ogUnlockDisk $3 $4
[e39921b]663return $ERRCODE
664}
665
666
667#/**
[914d834]668#         ogRestoreImage str_repo path_image int_ndisk int_npartition
669#@brief   Restaura una imagen de sistema de archivos en una partición.
670#@param   str_repo       repositorio de imágenes o caché local
671#@param   path_image     camino de la imagen
672#@param   int_ndisk      nº de orden del disco
673#@param   int_npartition nº de orden de la partición
674#@return  (por determinar)
[8e83677]675#@exception OG_ERR_FORMAT   1 formato incorrecto.
676#@exception OG_ERR_NOTFOUND  2 fichero de imagen o partición no detectados.
677#@exception OG_ERR_PARTITION 3  # Error en partición de disco.
678#@exception OG_ERR_LOCKED    4 partición bloqueada por otra operación.
679#@exception OG_ERR_IMAGE    5 error al restaurar la imagen del sistema.
680#@exception OG_ERR_IMGSIZEPARTITION  30 Tamaño de la particion es menor al tamaño de la imagen.
[914d834]681#@todo    Comprobar incongruencias partición-imagen, control de errores, definir parámetros, caché/repositorio, etc.
682#@version 0.1 -  Integracion para Opengnsys  - HIDRA:RestaurarImagen{EXT3, NTFS}.sh;  EAC: RestorePartitionFromImage() en Deploy.lib
683#@author Ramon Gomez, ETSII Universidad de Sevilla
684#@Date    2008/05/13
685#@author  Antonio J. Doblas Viso. Universidad de Malaga
686#@date    2008/10/27
687#@version 0.9 - Primera version muy en pruebas para OpenGnSys
688#@author  Ramon Gomez, ETSII Universidad de Sevilla
689#@date    2009/09/10
[8e83677]690#@version 1.0 - generacion sintaxis de restauracion
691#@author  Antonio J. Doblas Viso, Universidad de Malaga
692#@date    2011/02/01
693#@version 1.0.1 - Control errores, tamaño particion, fichero-imagen
694#@author  Antonio J. Doblas Viso, Universidad de Malaga
695#@date    2011/05/11
[914d834]696#*/ ##
697function ogRestoreImage ()
698{
699# Variables locales
[cbbb046]700local PART PARTSIZE IMGFILE IMGTYPE IMGSIZE FSTYPE PROGRAM ERRCODE
[914d834]701
702# Si se solicita, mostrar ayuda.
703if [ "$*" == "help" ]; then
704    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \
705           "$FUNCNAME REPO /aula1/winxp 1 1"
706    return
707fi
708# Error si no se reciben 4 parámetros.
[1f03f6e]709[ $# == 4 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]710# Procesar parámetros.
[8e83677]711PART="$(ogDiskToDev $3 $4)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
[914d834]712#IMGTYPE=$(ogGetImageType "$1" "$2")
713IMGTYPE=img
[8e83677]714IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
715[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
716# comprobamos consistencia de la imagen
717ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
718
[914d834]719# Error si la imagen no cabe en la particion.
[8e83677]720IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[be3b96a]721#TODO:
[8e83677]722#Si la particion no esta formateado o tiene problemas formateamos
723ogMount $3 $4 || ogFormat $3 $4
[f8b1b41]724PARTSIZE=$(ogGetPartitionSize $3 $4)
[914d834]725if [ $IMGSIZE -gt $PARTSIZE ]; then
[8e83677]726    ogRaiseError $OG_ERR_IMGSIZEPARTITION "  $PARTSIZE < $IMGSIZE"
[914d834]727    return $?
728fi
729# Comprobar el bloqueo de la imagen y de la partición.
730if ogIsImageLocked "$IMGFILE"; then
731    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
732    return $?
733fi
734if ogIsLocked $3 $4; then
735    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $3, $4"
736    return $?
737fi
[2fc81c4]738
739# Solicitamos la generación de la instruccion a ejecutar
740# Atención: no se comprueba el tipo de sistema de archivos.
741# Atención: no se comprueba incongruencia entre partición e imagen.
742PROGRAM=`ogRestoreImageSyntax  $IMGFILE $PART`
743
[914d834]744# Desmontar y bloquear partición.
[8e83677]745ogUnmount $3 $4 2>/dev/null || return $(ogRaiseError $OG_ERR_PARTITION " $3 $4"; echo $?)
[a73649d]746ogLock $3 $4 || return $?
[914d834]747trap "ogUnlock $3 $4" 1 2 3 6 9
748
[2fc81c4]749# Ejecutar restauración según el tipo de imagen.
[914d834]750eval $PROGRAM
751
752ERRCODE=$?
753if [ $ERRCODE != 0 ]; then
754    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
755fi
756ogUnlock $3 $4
757return $ERRCODE
758}
759
760
761#/**
[a25cc03]762#         ogRestoreMbrImage str_repo path_image int_ndisk
763#@brief   Restaura la imagen del sector de arranque de un disco.
764#@param   str_repo     repositorio de imágenes o caché local
765#@param   path_image   camino de la imagen
766#@param   int_ndisk    nº de orden del disco
767#@return  (por determinar)
768#@exception OG_ERR_FORMAT   formato incorrecto.
769#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
770#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
771#@version 0.9 - Primera versión en pruebas.
772#@author  Ramon Gomez, ETSII Universidad de Sevilla
773#@date    2010/01/12
774#@version 1.0 - Adaptación a OpenGnSys 1.0
775#@author  Ramon Gomez, ETSII Universidad de Sevilla
776#@date    2011/03/10
777#*/ ##
778function ogRestoreMbrImage ()
779{
780# Variables locales
781local DISK IMGFILE
782# Si se solicita, mostrar ayuda.
783if [ "$*" == "help" ]; then
784    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
785           "$FUNCNAME REPO /aula1/mbr 1"
786    return
787fi
788# Error si no se reciben 3 parámetros.
[a73649d]789[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]790# Procesar parámetros.
791DISK=$(ogDiskToDev "$3") || return $?
792IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
[8e65e89]793[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[a25cc03]794
795# Restaurar imagen del MBR.
796dd if="$IMGFILE" of="$DISK" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
797}
798
799
800#/**
[b52e658]801#         ogRestoreBootLoaderImage str_repo path_image int_ndisk
802#@brief   Restaura la imagen del boot loader del sector de arranque de un disco.
803#@param   str_repo     repositorio de imágenes o caché local
804#@param   path_image   camino de la imagen
805#@param   int_ndisk    nº de orden del disco
806#@return  (por determinar)
807#@exception OG_ERR_FORMAT   formato incorrecto.
808#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
809#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
810#@version 1.0 - Adaptacion de ogRestoreMbrImage para restaurar solo el Boot Loader
811#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
812#@date    2011/03/21
813#*/ ##
814function ogRestoreBootLoaderImage ()
815{
816# Variables locales
817local DISK IMGFILE
818# Si se solicita, mostrar ayuda.
819if [ "$*" == "help" ]; then
820    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
821           "$FUNCNAME REPO /aula1/mbr 1"
822    return
823fi
824# Error si no se reciben 3 parámetros.
[a73649d]825[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]826# Procesar parámetros.
827DISK=$(ogDiskToDev "$3") || return $?
828IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
[8e65e89]829[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[b52e658]830
831# Restaurar imagen del MBR.
832dd if="$IMGFILE" of="$DISK" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
833}
834
835#/**
[a25cc03]836#         ogUnlockImage [str_repo] path_image
837#@brief   Desbloquea una imagen con uso exclusivo.
838#@param   str_repo     repositorio de imágenes (opcional)
839#@param   path_image   camino de la imagen (sin extensión)
840#@return  Nada.
841#@note    repo = { REPO, CACHE }
842#@note    Se elimina el fichero de bloqueo con extensión .lock
843#@exception OG_ERR_FORMAT    formato incorrecto.
844#@version 1.0 - Adaptación a OpenGnSys 1.0
845#@author  Ramon Gomez, ETSII Universidad de Sevilla
846#@date    2011/03/10
847#*/ ##
848function ogUnlockImage ()
849{
850# Si se solicita, mostrar ayuda.
851if [ "$*" == "help" ]; then
852    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
853           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
854           "$FUNCNAME REPO /aula1/winxp.img"
855    return
856fi
857# Error si no se reciben 1 o 2 parámetros.
[a73649d]858[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]859
860# Borrar fichero de bloqueo para la imagen.
861rm -f $(ogGetPath $@.lock)
862}
863
864
865#/**
[914d834]866#         ogGetImageInfo filename
867#@brief   muestra información sobre la imagen monolitica.
868#@param 1   filename           path absoluto del fichero imagen
869#@return  cadena compuesta por clonacion:compresor:sistemaarchivos:tamañoKB
870#@exception OG_ERR_FORMAT    formato incorrecto.
871#@exception OG_ERR_NOTFOUND   fichero no encontrado.
872#@exception OG_ERR_IMAGE        "Image format is not valid $IMGFILE"
873#@warning En pruebas iniciales
874#@TODO    Definir sintaxis de salida (herramienta y compresor en minuscula)
875#@TODO    Arreglar loop para ntfsclone
876#@TODO    insertar parametros entrada tipo OG
877#@version 1.0 - Primeras pruebas
878#@author  Antonio J. Doblas Viso. Universidad de Málaga
879#@date    2010/02/08
880#*/ ##
881
[cbbb046]882function ogGetImageInfo ()
883{
[914d834]884# Si se solicita, mostrar ayuda.
885if [ "$*" == "help" ]; then
886    ogHelp "$FUNCNAME" "$FUNCNAME  filename " \
887           "$FUNCNAME  /opt/opengnsys/images/prueba.img "
888    return
889fi
890
891# Error si no se reciben 1 parámetros.
892[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
893
894#comprobando que el parametro uno es un file.
895[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
896
[51953ae]897local TOOLS COMPRESSOR IMGFILE FILEHEAD FS FSPLUS SIZE SIZEFACTOR PARTIMAGEINFO PARTCLONEINFO NTFSCLONEINFO IMGDETECT
[914d834]898IMGDETECT="FALSE"
899
900IMGFILE=$1
901FILEHEAD=/tmp/`basename $IMGFILE`.infohead
902COMPRESSOR=`file $IMGFILE | awk '{print $2}'`
903ogCheckStringInGroup "$COMPRESSOR" "gzip lzop" || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
904$($COMPRESSOR -dc $IMGFILE 2>/dev/null | head > $FILEHEAD) || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
905
906## buscando Primera opción.
907if [ "$IMGDETECT" == "FALSE" ]
908then
[8e9669e]909        PARTCLONEINFO=$(LC_ALL=C partclone.info $FILEHEAD 2>&1)
[914d834]910        if `echo $PARTCLONEINFO | grep size > /dev/null`
911        then
912                TOOLS=PARTCLONE
913                FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}')
[d2f8c5a]914                if [[ "$FS" == "HFS" || "$FS" == "HFSPLUS" || "$FS" == "FAT32" ]]; then
[1cbf9e0]915                        FSPLUS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($9);}')
916                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
[1131208]917                        if [ "$FSPLUS" == "PLUS" ]; then
[1cbf9e0]918                                FS=$FS$FSPLUS
919                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $17*FACTOR;}')
920                        else
921                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $16*FACTOR;}')
922                        fi
923                else
924                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
925                        SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}')
926                fi
[914d834]927                IMGDETECT="TRUE"
928        fi
929fi
930#buscando segunda opcion.
931if [ "$IMGDETECT" == "FALSE" -a ! -f /dev/loop2  ]
932then
933        cat $FILEHEAD | grep -w ntfsclone-image > /dev/null && NTFSCLONEINFO=$(cat $FILEHEAD | ntfsclone --restore --overwrite /dev/loop2 - 2>&1)
934        if `echo $NTFSCLONEINFO | grep ntfsclone > /dev/null` 
935        then
936                TOOLS=NTFSCLONE
937                SIZE=$(echo $NTFSCLONEINFO | awk '{gsub(/\(|\)|\./,""); printf "%d\n",$17/1000;}')
938                FS=NTFS
939                IMGDETECT="TRUE"
940        fi
941fi
942## buscando Tercer opción.
943if [ "$IMGDETECT" == "FALSE" ]
944then
945        PARTIMAGEINFO=$(partimage -B gui=no imginfo "$FILEHEAD" 2>&1)
946        if `echo $PARTIMAGEINFO | grep Partition > /dev/null`
947        then   
948                TOOLS=PARTIMAGE
949                FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}')
950                SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}')
951                IMGDETECT="TRUE"
[1feb465]952        fi
953        if file $FILEHEAD 2> /dev/null | grep -q "boot sector"; then
[a30ad15f]954                TOOLS="partclone.dd"
[1feb465]955                FS=
956                SIZE=
957                IMGDETECT="TRUE"
958        fi
[914d834]959fi
960#comprobamos valores #Chequeamos los valores devueltos.
961if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ]
962then
963        ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
964else
965        COMPRESSOR=$(echo $COMPRESSOR | tr [a-z] [A-Z])
966        echo $TOOLS:$COMPRESSOR:$FS:$SIZE
967fi
968}
969
970function ogGetImageProgram ()
971{
972local IMGFILE
973IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]974[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]975ogGetImageInfo $IMGFILE | awk -F: '{print $1}'
976
977}
978
979function ogGetImageCompressor ()
980{
981local IMGFILE
982IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]983[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]984ogGetImageInfo $IMGFILE | awk -F: '{print $2}'
985}
986
987function ogGetImageType ()
988{
989local IMGFILE
990IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]991[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]992#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
993#        awk '/^Filesystem/ {sub(/\.\.+/," "); sub(/fs$/,""); print toupper($2);}'
994ogGetImageInfo $IMGFILE | awk -F: '{print $3}'
995
996}
997
998function ogGetImageSize ()
999{
1000# Variables locales
1001local IMGFILE
1002
1003# Si se solicita, mostrar ayuda.
1004if [ "$*" == "help" ]; then
[8e83677]1005    ogHelp "$FUNCNAME" "$FUNCNAME REPO|CACHE /str_image" \
1006           "$FUNCNAME REPO /aula1/winxp  ==>  5642158"
[914d834]1007    return
1008fi
[a73649d]1009# Error si no se reciben 2 parámetros.
1010[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]1011# Error si el fichero de imagen no es accesible.
1012IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]1013[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1014
1015# Devuelve el tamaño de la imagen en KB.
1016#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
1017#        awk '/Partition size/ {sub(/\.\.+/," "); printf "%d\n",$3*1024*1024;}'
1018ogGetImageInfo $IMGFILE | awk -F: '{print $4}'
1019}
1020
Note: See TracBrowser for help on using the repository browser.