source: client/engine/Boot.lib @ 1c74bf5

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-instalacion
Last change on this file since 1c74bf5 was e9601e1, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #889 #890 ogGrubInstallPartitions, ogGrubInstallMbr y ogRestoreEfiBootLoader: Format EFI partition if it is not. ogGetEsp: Detecting the EFI partition does not require VFAT filesystem.

  • Property mode set to 100755
File size: 83.9 KB
Line 
1#!/bin/bash
2#/**
3#@file    Boot.lib
4#@brief   Librería o clase Boot
5#@class   Boot
6#@brief   Funciones para arranque y post-configuración de sistemas de archivos.
7#@version 1.1.0
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogBoot int_ndisk int_nfilesys [str_kernel str_initrd str_krnlparams]
14#@brief   Inicia el proceso de arranque de un sistema de archivos.
15#@param   int_ndisk      nº de orden del disco
16#@param   int_nfilesys   nº de orden del sistema de archivos
17#@param   str_krnlparams parámetros de arranque del kernel (opcional)
18#@return  (activar el sistema de archivos).
19#@exception OG_ERR_FORMAT    Formato incorrecto.
20#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
21#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
22#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
23#@note    En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB.
24#@note    En Linux, debe arrancarse la partición del directorio \c /boot
25#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib 
26#@author  Antonio J. Doblas Viso, Universidad de Malaga
27#@date    2008-10-27
28#@version 0.9 - Adaptación para OpenGnSys.
29#@author  Ramon Gomez, ETSII Universidad de Sevilla
30#@date    2009-09-11
31#@version 1.0.4 - Soporta modo de arranque Windows (parámetro de inicio "winboot").
32#@author  Ramon Gomez, ETSII Universidad de Sevilla
33#@date    2012-04-12
34#@version 1.0.6 - Selección a partir de tipo de sistema operativo (en vez de S.F.) y arrancar Linux con /boot separado.
35#@author  Ramon Gomez, ETSII Universidad de Sevilla
36#@date    2015-06-05
37#@version 1.1.0 - Nuevo parámetro opcional con opciones de arranque del Kernel.
38#@author  Ramon Gomez, ETSII Universidad de Sevilla
39#@date    2015-07-15
40#*/ ##
41function ogBoot ()
42{
43# Variables locales.
44local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
45local EFIDISK EFIPART EFIDIR BOOTLABEL BOOTNO DIRGRUB b
46
47# Si se solicita, mostrar ayuda.
48if [ "$*" == "help" ]; then
49    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_kernel str_initrd str_kernelparams]" \
50           "$FUNCNAME 1 1" "$FUNCNAME 1 2 \"/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro\""
51    return
52fi
53# Error si no se reciben 2 o 3 parámetros.
54[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
55
56# Detectar tipo de sistema de archivos y montarlo.
57PART=$(ogDiskToDev $1 $2) || return $?
58TYPE=$(ogGetOsType $1 $2) || return $?
59# Error si no puede montar sistema de archivos.
60MNTDIR=$(ogMount $1 $2) || return $?
61
62case "$TYPE" in
63    Linux|Android)
64        # Si no se indican, obtiene los parámetros de arranque para Linux.
65        PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}"
66        # Si no existe, buscar sistema de archivo /boot en /etc/fstab.
67        if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then
68            # Localizar S.F. /boot en /etc/fstab del S.F. actual.
69            PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
70            # Montar S.F. de /boot.
71            MNTDIR=$(ogMount $PART) || return $?
72            # Buscar los datos de arranque.
73            PARAMS=$(ogLinuxBootParameters $PART) || exit $?
74        fi
75        read -e KERNEL INITRD APPEND <<<"$PARAMS"
76        # Si no hay kernel, no hay sistema operativo.
77        [ -n "$KERNEL" -a -e "$MNTDIR/$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
78        # Arrancar de partición distinta a la original.
79        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
80        # Comprobar tipo de sistema.
81        if ogIsEfiActive; then
82            # Comprobar si el Kernel está firmado.
83            if ! file -k "$MNTDIR/$KERNEL" | grep -q "EFI app"; then
84                ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)"
85                return $?
86            fi
87            ### Se realiza en la postconfiguracion ¿lo volvemos a hacer aquí?
88            ## Configuramos el grub.cfg de la partición EFI
89            ## Directorio del grub en la partición de sistema
90            #for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
91            #    [ -r $f ] && DIRGRUB=$(dirname $f)
92            #done
93            #DIRGRUB=${DIRGRUB#$MNTDIR/}
94            #ogGrubUefiConf $1 $2 $DIRGRUB || return $?
95
96            # Borrar cargador guardado con la misma etiqueta.
97            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
98            BOOTNO=$(efibootmgr -v | awk -v L=$BOOTLABEL '{if ($2==L) print $1}')
99            for b in $BOOTNO; do
100                efibootmgr -B -b ${b:4:4} &>/dev/null
101            done
102            # Obtener parcición EFI.
103            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
104            # Crear orden de arranque (con unos valores por defecto).
105            efibootmgr -C -d $(ogDiskToDev $EFIDISK) -p $EFIPART -L "$BOOTLABEL" -l "/EFI/$BOOTLABEL/grubx64.efi" &>/dev/null
106            # Marcar próximo arranque y reiniciar.
107            BOOTNO=$(efibootmgr -v | awk -v L="$BOOTLABEL" '{if ($2==L) print $1}')
108            [ -n "$BOOTNO" ] && efibootmgr -n ${BOOTNO:4:4} &>/dev/null
109            # Incluimos en el orden de arranque
110            BOOTORDER=$(efibootmgr | awk -v L="BootOrder:" '{if ($1==L) print $2}')
111            [[ $BOOTORDER =~ ${BOOTNO:4:4} ]] || efibootmgr -o $BOOTORDER,${BOOTNO:4:4}
112            reboot
113        else
114            # Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB.
115            kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
116            kexec -e &
117        fi
118        ;;
119    Windows)
120        # Comprobar tipo de sistema.
121        if ogIsEfiActive; then
122            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
123            # Obtener parcición EFI.
124            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
125            [ -n "$EFIPART" ] || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
126            EFIDIR=$(ogMount $EFIDISK $EFIPART) || exit $?
127            # Comprobar cargador (si no existe buscar por defecto en ESP).
128            #LOADER=$(ogGetPath $1 $2 /Boot/bootmgfw.efi)
129            LOADER=$(ogGetPath $EFIDIR/EFI/$BOOTLABEL/Boot/bootmgfw.efi)
130            [ -z "$LOADER" ] && BOOTLABEL=Microsoft && LOADER=$(ogGetPath $EFIDIR/EFI/Microsoft/Boot/bootmgfw.efi)
131            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)" || return $?
132            # El directorio se crea en la postconfiguración
133            ## Crear directorio para el cargador y copiar los ficheros.
134            #mkdir -p $EFIDIR/EFI/$BOOTLABEL
135            #cp -a $(dirname "$LOADER") $EFIDIR/EFI/$BOOTLABEL
136            # Borrar cargador guardado con la misma etiqueta.
137            BOOTNO=$(efibootmgr -v | awk -v L=$BOOTLABEL '{if ($2==L) print $1}')
138            [ -n "$BOOTNO" ] && efibootmgr -B -b ${BOOTNO:4:4}
139            # Crear orden de arranque (con unos valores por defecto).
140            efibootmgr -C -d $(ogDiskToDev $EFIDISK) -p $EFIPART -L "$BOOTLABEL" -l "/EFI/$BOOTLABEL/Boot/BOOTMGFW.EFI"
141            # Marcar próximo arranque y reiniciar.
142            BOOTNO=$(efibootmgr -v | awk -v L="$BOOTLABEL" '{if ($2==L) print $1}')
143            [ -n "$BOOTNO" ] && efibootmgr -n ${BOOTNO:4:4}
144            reboot
145        else
146            # Arranque BIOS: comprueba si hay un cargador de Windows.
147            for f in io.sys ntldr bootmgr; do
148                FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
149                [ -n "$FILE" ] && LOADER="$f"
150            done
151            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
152            if [ "$winboot" == "kexec" ]; then
153                # Modo de arranque en caliente (con kexec).
154                cp $OGLIB/grub4dos/* $MNTDIR    # */ (Comentario Doxygen)
155                kexec -l $MNTDIR/grub.exe --append=--config-file="root (hd$[$1-1],$[$2-1]); chainloader (hd$[$1-1],$[$2-1])/$LOADER; tpm --init"
156                kexec -e &
157            else
158                # Modo de arranque por reinicio (con reboot).
159                dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3
160                dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3
161                dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3
162                if  [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then
163                    ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot'
164                    ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*"
165                fi
166                # Activar la partición.
167                ogSetPartitionActive $1 $2
168                reboot
169            fi
170        fi
171        ;;
172    MacOS)
173        # Modo de arranque por reinicio.
174        # Nota: el cliente tiene que tener configurado correctamente Grub.
175        touch ${MNTDIR}/boot.mac &>/dev/null
176        reboot
177        ;;
178    GrubLoader)
179        # Reiniciar.
180        #reboot
181        ;;
182    *)  ogRaiseError $OG_ERR_NOTOS "$1 $2 ${TYPE:+($TYPE)}"
183        return $?
184        ;;
185esac
186}
187
188
189#/**
190#         ogGetWindowsName int_ndisk int_nfilesys
191#@brief   Muestra el nombre del equipo en el registro de Windows.
192#@param   int_ndisk      nº de orden del disco
193#@param   int_nfilesys   nº de orden del sistema de archivos
194#@return  str_name - nombre del equipo
195#@exception OG_ERR_FORMAT    Formato incorrecto.
196#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
197#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
198#@version 0.9 - Adaptación para OpenGnSys.
199#@author  Ramon Gomez, ETSII Universidad de Sevilla
200#@date    2009-09-23
201#*/ ##
202function ogGetWindowsName ()
203{
204# Variables locales.
205local MNTDIR
206
207# Si se solicita, mostrar ayuda.
208if [ "$*" == "help" ]; then
209    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
210           "$FUNCNAME 1 1  ==>  PRACTICA-PC"
211    return
212fi
213# Error si no se reciben 2 parámetros.
214[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
215
216# Montar el sistema de archivos.
217MNTDIR=$(ogMount $1 $2) || return $?
218
219# Obtener dato del valor de registro.
220ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
221}
222
223
224#/**
225#         ogLinuxBootParameters int_ndisk int_nfilesys
226#@brief   Muestra los parámetros de arranque de un sistema de archivos Linux.
227#@param   int_ndisk      nº de orden del disco
228#@param   int_nfilesys   nº de orden del sistema de archivos
229#@return  str_kernel str_initrd str_parameters ...
230#@exception OG_ERR_FORMAT    Formato incorrecto.
231#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
232#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
233#@warning Función básica usada por \c ogBoot
234#@version 0.9 - Primera adaptación para OpenGnSys.
235#@author  Ramon Gomez, ETSII Universidad de Sevilla
236#@date    2009-09-11
237#@version 0.9.2 - Soporta partición /boot independiente.
238#@author  Ramon Gomez, ETSII Universidad de Sevilla
239#@date    2010-07-20
240#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
241#@author  Ramon Gomez, ETSII Universidad de Sevilla
242#@date    2013-05-14
243#@version 1.0.6 - Detectar instalaciones sobre EFI.
244#@author  Ramon Gomez, ETSII Universidad de Sevilla
245#@date    2014-09-15
246#*/ ##
247function ogLinuxBootParameters ()
248{
249# Variables locales.
250local MNTDIR CONFDIR CONFFILE f
251
252# Si se solicita, mostrar ayuda.
253if [ "$*" == "help" ]; then
254    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
255           "$FUNCNAME 1 2  ==>  /vmlinuz-3.5.0-21-generic /initrd.img-3.5.0-21-generic root=/dev/sda2 ro splash"
256    return
257fi
258# Error si no se reciben 2 parámetros.
259[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
260
261# Detectar id. de tipo de partición y codificar al mnemonico.
262MNTDIR=$(ogMount $1 $2) || return $?
263
264# Fichero de configuración de GRUB.
265CONFDIR=$MNTDIR                               # Sistema de archivos de arranque (/boot).
266[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot   # Sist. archivos raíz con directorio boot.
267for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
268    [ -r $f ] && CONFFILE=$f
269done
270[ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
271
272# Toma del fichero de configuracion los valores del kernel, initrd
273#       y parámetros de arranque usando las cláusulas por defecto
274#       ("default" en GRUB1, "set default" en GRUB2)
275#       y los formatea para que sean compatibles con \c kexec .  */
276# /* (comentario Doxygen)
277awk 'BEGIN {cont=-1;}
278     $1~/^default$/     {sub(/=/," "); def=$2;}
279     $1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3;
280                                   if (def ~ /saved_entry/) def=0;
281                                 }
282     $1~/^(title|menuentry)$/ {cont++}
283     $1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; }
284     $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
285                                       kern=$2;
286                                       sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
287                                      } # /* (comentario Doxygen)
288                                    }
289     $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
290     END {if (kern!="") printf("%s %s %s", kern,init,app)}
291    ' $CONFFILE
292# */ (comentario Doxygen)
293}
294
295
296#/**
297#         ogSetWindowsName int_ndisk int_nfilesys str_name
298#@brief   Establece el nombre del equipo en el registro de Windows.
299#@param   int_ndisk      nº de orden del disco
300#@param   int_nfilesys   nº de orden del sistema de archivos
301#@param   str_name       nombre asignado
302#@return  (nada)
303#@exception OG_ERR_FORMAT     Formato incorrecto.
304#@exception OG_ERR_NOTFOUND   Disco o particion no corresponden con un dispositivo.
305#@exception OG_ERR_PARTITION  Tipo de partición desconocido o no se puede montar.
306#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
307#@version 0.9 - Adaptación a OpenGnSys.
308#@author  Ramon Gomez, ETSII Universidad de Sevilla
309#@date    2009-09-24
310#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
311#@author  Ramon Gomez, ETSII Universidad de Sevilla
312#@date    2013-03-20
313#*/ ##
314function ogSetWindowsName ()
315{
316# Variables locales.
317local PART MNTDIR NAME
318
319# Si se solicita, mostrar ayuda.
320if [ "$*" == "help" ]; then
321    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
322           "$FUNCNAME 1 1 PRACTICA-PC"
323    return
324fi
325# Error si no se reciben 3 parámetros.
326[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
327# Error si el nombre supera los 15 caracteres.
328[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
329
330# Montar el sistema de archivos.
331MNTDIR=$(ogMount $1 $2) || return $?
332
333# Asignar nombre.
334NAME="$3"
335
336# Modificar datos de los valores de registro.
337ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
338ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
339ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\HostName' "$NAME" 2>/dev/null
340ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
341ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
342ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV HostName' "$NAME" 2>/dev/null
343ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
344}
345
346
347#/**
348#         ogSetWinlogonUser int_ndisk int_npartition str_username
349#@brief   Establece el nombre de usuario por defecto en la entrada de Windows.
350#@param   int_ndisk      nº de orden del disco
351#@param   int_npartition nº de orden de la partición
352#@param   str_username   nombre de usuario por defecto
353#@return  (nada)
354#@exception OG_ERR_FORMAT    Formato incorrecto.
355#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
356#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
357#@version 0.9.2 - Adaptación a OpenGnSys.
358#@author  Ramon Gomez, ETSII Universidad de Sevilla
359#@date    2010-07-20
360#*/ ##
361function ogSetWinlogonUser ()
362{
363# Variables locales.
364local PART MNTDIR NAME
365
366# Si se solicita, mostrar ayuda.
367if [ "$*" == "help" ]; then
368    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
369           "$FUNCNAME 1 1 USUARIO"
370    return
371fi
372# Error si no se reciben 3 parámetros.
373[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
374
375# Montar el sistema de archivos.
376MNTDIR=$(ogMount $1 $2) || return $?
377
378# Asignar nombre.
379NAME="$3"
380
381# Modificar datos en el registro.
382ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
383}
384
385
386#/**
387#         ogBootMbrXP int_ndisk
388#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
389#@param   int_ndisk      nº de orden del disco
390#@return  salida del programa my-sys
391#@exception OG_ERR_FORMAT    Formato incorrecto.
392#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
393#@version 0.9 - Adaptación a OpenGnSys.
394#@author  Antonio J. Doblas Viso. Universidad de Málaga
395#@date    2009-09-24
396#*/ ##
397
398function ogBootMbrXP ()
399{
400# Variables locales.
401local DISK
402
403# Si se solicita, mostrar ayuda.
404if [ "$*" == "help" ]; then
405    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
406           "$FUNCNAME 1"
407    return
408fi
409# Error si no se recibe 1 parámetro.
410[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
411
412DISK="$(ogDiskToDev $1)" || return $?
413ms-sys -z -f $DISK
414ms-sys -m -f $DISK
415}
416
417
418#/**
419#         ogBootMbrGeneric int_ndisk
420#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
421#@param   int_ndisk      nº de orden del disco
422#@return  salida del programa my-sys
423#@exception OG_ERR_FORMAT    Formato incorrecto.
424#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
425#@version 0.9 - Adaptación a OpenGnSys.
426#@author  Antonio J. Doblas Viso. Universidad de Málaga
427#@date    2009-09-24
428#*/ ##
429
430function ogBootMbrGeneric ()
431{
432# Variables locales.
433local DISK
434
435# Si se solicita, mostrar ayuda.
436if [ "$*" == "help" ]; then
437    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
438           "$FUNCNAME 1 "
439    return
440fi
441# Error si no se recibe 1 parámetro.
442[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
443
444DISK="$(ogDiskToDev $1)" || return $?
445ms-sys -z -f $DISK
446ms-sys -s -f $DISK
447}
448
449
450
451
452#/**
453#         ogFixBootSector int_ndisk int_parition
454#@brief   Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
455#@param   int_ndisk      nº de orden del disco
456#@param   int_partition     nº de particion
457#@return 
458#@exception OG_ERR_FORMAT    Formato incorrecto.
459#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
460#@version 0.9 - Adaptación a OpenGnSys.
461#@author  Antonio J. Doblas Viso. Universidad de Málaga
462#@date    2009-09-24
463#*/ ##
464
465function ogFixBootSector ()
466{
467# Variables locales.
468local PARTYPE DISK PART FILE
469
470# Si se solicita, mostrar ayuda.
471if [ "$*" == "help" ]; then
472    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
473           "$FUNCNAME 1 1 "
474    return
475fi
476
477# Error si no se reciben 2 parámetros.
478[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
479
480#TODO, solo si la particion existe
481#TODO, solo si es ntfs o fat
482PARTYPE=$(ogGetPartitionId $1 $2)
483case "$PARTYPE" in
484        1|4|6|7|b|c|e|f|17|700|EF00)
485        ;;
486        *)
487        return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
488        ;;
489esac
490
491ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
492
493#Preparando instruccion
494let DISK=$1-1   
495PART=$2
496FILE=/tmp/temp$$
497cat > $FILE <<EOF
498disk=$DISK
499main_part=$PART
500fix_first_sector=yes
501EOF
502
503timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -a -f $FILE
504rm -f $FILE
505}
506
507
508
509#/**
510#         ogWindowsBootParameters int_ndisk int_parition
511#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
512#@param   int_ndisk      nº de orden del disco
513#@param   int_partition     nº de particion
514#@return 
515#@exception OG_ERR_FORMAT    Formato incorrecto.
516#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
517#@version 0.9 - Integración desde EAC para OpenGnSys.
518#@author  Antonio J. Doblas Viso. Universidad de Málaga
519#@date    2009-09-24
520#@version 1.0.1 - Adapatacion para OpenGnsys.
521#@author  Antonio J. Doblas Viso. Universidad de Málaga
522#@date    2011-05-20
523#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
524#@author  Ramon Gomez, ETSII Universidad de Sevilla
525#@date    2014-01-28
526#@version 1.1.0 - Soporte para Windows 10.
527#@author  Ramon Gomez, ETSII Universidad de Sevilla
528#@date    2016-01-19
529#@version 1.1.1 - Compatibilidad con UEFI (ticket #802 #889)
530#@author  Irina Gomez, ETSII Universidad de Sevilla
531#@date    2019-01-28
532#*/ ##
533
534function ogWindowsBootParameters ()
535{
536# Variables locales.
537local PART DISK BOOTLABEL BCDFILE BOOTDISK BOOTPART FILE WINVER MOUNT
538
539# Si se solicita, mostrar ayuda.
540if [ "$*" == "help" ]; then
541    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
542           "$FUNCNAME 1 1 "
543    return
544fi
545
546# Error si no se reciben 2 parámetros.
547[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
548
549ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
550
551#Preparando variables adaptadas a sintaxis windows.
552let DISK=$1-1
553PART=$2
554FILE=/tmp/temp$$
555if [ ogIsEfiActive ]; then
556    read BOOTDISK BOOTPART <<< $(ogGetEsp)
557    ogUnmount $BOOTDISK $BOOTPART || ogRaiseError $OG_ERR_PARTITION "ESP: $BOOTDISK $BOOTPART" || return $?
558
559    let BOOTDISK=$BOOTDISK-1
560    BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
561    BCDFILE="boot_BCD_file=/EFI/$BOOTLABEL/Boot/BCD"
562else
563    BOOTDISK=$DISK
564    BOOTPART=$PART
565    BCDFILE=""
566fi
567
568
569# Obtener versión de Windows.
570WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
571[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?)
572
573# Acciones para Windows XP.
574if [[ "$WINVER" =~ "XP" ]]; then
575    MOUNT=$(ogMount $1 $2)
576    [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?)
577    cat ${MOUNT}/boot.ini | sed s/partition\([0-9]\)/partition\($PART\)/g | sed s/rdisk\([0-9]\)/rdisk\($DISK\)/g > ${MOUNT}/tmp.boot.ini; mv ${MOUNT}/tmp.boot.ini ${MOUNT}/boot.ini
578    return 0
579fi
580
581ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
582
583
584#Preparando instruccion Windows Resume Application
585cat > $FILE <<EOF
586boot_disk=$BOOTDISK
587boot_main_part=$BOOTPART
588$BCDFILE
589disk=$DISK
590main_part=$PART
591boot_entry=Windows Resume Application
592EOF
593timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
594
595
596#Preparando instruccion tipo windows
597cat > $FILE <<EOF
598boot_disk=$BOOTDISK
599boot_main_part=$BOOTPART
600$BCDFILE
601disk=$DISK
602main_part=$PART
603boot_entry=$WINVER
604EOF
605timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
606
607##Preparando instruccion        Ramdisk Options
608cat > $FILE <<EOF
609boot_disk=$BOOTDISK
610boot_main_part=$BOOTPART
611$BCDFILE
612disk=$DISK
613main_part=$PART
614boot_entry=Ramdisk Options
615EOF
616timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
617
618##Preparando instruccion        Recovery Environment
619cat > $FILE <<EOF
620boot_disk=$BOOTDISK
621boot_main_part=$BOOTPART
622$BCDFILE
623disk=$DISK
624main_part=$PART
625boot_entry=Windows Recovery Environment
626EOF
627timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
628
629##Preparando instruccion        Recovery
630cat > $FILE <<EOF
631boot_disk=$BOOTDISK
632boot_main_part=$BOOTPART
633$BCDFILE
634disk=$DISK
635main_part=$PART
636boot_entry=Windows Recovery
637EOF
638timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
639
640#Preparando instruccion Windows Boot Manager
641cat > $FILE <<EOF
642boot_disk=$BOOTDISK
643boot_main_part=$BOOTPART
644$BCDFILE
645disk=$BOOTDISK
646main_part=$BOOTPART
647boot_entry=Windows Boot Manager
648EOF
649timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
650
651#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
652cat > $FILE <<EOF
653boot_disk=$BOOTDISK
654boot_main_part=$BOOTPART
655$BCDFILE
656disk=$BOOTDISK
657main_part=$BOOTPART
658boot_entry=Herramienta de diagnóstico de memoria de Windows
659EOF
660timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
661
662#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
663cat > $FILE <<EOF
664boot_disk=$BOOTDISK
665boot_main_part=$BOOTPART
666$BCDFILE
667disk=$BOOTDISK
668main_part=$BOOTPART
669boot_entry=Herramienta de diagn<f3>stico de memoria de Windows
670EOF
671timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
672
673rm -f $FILE
674}
675
676
677
678#/**
679#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
680#@brief   Registra una partición en windows con un determinado volumen.
681#@param   int_ndisk      nº de orden del disco a registrar
682#@param   int_partition     nº de particion a registrar
683#@param   str_volumen      volumen a resgistar
684#@param   int_ndisk_windows      nº de orden del disco donde esta windows
685#@param   int_partition_windows     nº de particion donde esta windows
686#@return 
687#@exception OG_ERR_FORMAT    Formato incorrecto.
688#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
689#@version 0.9 - Adaptación a OpenGnSys.
690#@author  Antonio J. Doblas Viso. Universidad de Málaga
691#@date    2009-09-24
692#*/ ##
693function ogWindowsRegisterPartition ()
694{
695# Variables locales.
696local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
697
698# Si se solicita, mostrar ayuda.
699if [ "$*" == "help" ]; then
700    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
701           "$FUNCNAME 1 1 c: 1 1"
702    return
703fi
704
705# Error si no se reciben 5 parámetros.
706[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
707
708REGISTREDDISK=$1
709REGISTREDPART=$2
710REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
711DISK=$4
712PART=$5
713FILE=/tmp/temp$$
714
715ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
716ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
717
718ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
719
720VERSION=$(ogGetOsVersion $DISK $PART)
721
722#Systemroot
723
724if ogGetPath $DISK $PART WINDOWS
725then
726        SYSTEMROOT="Windows"
727elif ogGetPath $DISK $PART WINNT
728then
729        SYSTEMROOT="winnt"
730else
731        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
732fi
733
734ogUnmount $DISK $PART
735let DISK=$DISK-1
736let REGISTREDDISK=$REGISTREDDISK-1
737#Preparando instruccion Windows Boot Manager
738cat > $FILE <<EOF
739windows_disk=$DISK
740windows_main_part=$PART
741windows_dir=$SYSTEMROOT
742disk=$REGISTREDDISK
743main_part=$REGISTREDPART
744;ext_part
745part_letter=$REGISTREDVOL
746EOF
747timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -u -f $FILE
748
749}
750
751#/**
752#         ogGrubInstallMbr  int_disk_GRUBCFG  int_partition_GRUBCFG 
753#@brief   Instala el grub el el MBR del primer disco duro (FIRSTSTAGE). El fichero de configuración grub.cfg ubicado según parametros disk y part(SECONDSTAGE). Admite sistemas Windows.
754#@param   int_disk_SecondStage     
755#@param   int_part_SecondStage     
756#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
757#@return 
758#@exception OG_ERR_FORMAT    Formato incorrecto.
759#@version 1.0.2 - Primeras pruebas.
760#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
761#@date    2011-10-29
762#@version 1.0.3 - Soporte para linux de 32 y 64 bits
763#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
764#@date    2012-03-13
765#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
766#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
767#@date    2012-03-13
768#@version 1.1.0 - #791 El FIRSTSTAGE(MBR) siempre será el primer disco duro. EL SECONDSTAGE(grub.cfg) estára en el DISK y PART indicados en los parámetros.
769#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
770#@date    2017-06-19
771#@version 1.1.0 - #827 Entrada para el ogLive si el equipo tiene partición cache.
772#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
773#@date    2018-01-21
774#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
775#@author Irina Gomez, ETSII Universidad de Sevilla
776#@date    2019-01-08
777#*/ ##
778
779function ogGrubInstallMbr ()
780{
781
782# Variables locales.
783local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
784local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
785
786# Si se solicita, mostrar ayuda.
787if [ "$*" == "help" ]; then
788    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
789           "$FUNCNAME 1 1 FALSE " \
790           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
791    return
792fi 
793
794# Error si no se reciben 2 parámetros.
795[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
796
797
798DISK=$1; PART=$2;
799CHECKOS=${3:-"FALSE"}
800KERNELPARAM=$4
801BACKUPNAME=".backup.og"
802
803#Error si no es linux.
804#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
805#VERSION=$(ogGetOsVersion $DISK $PART)
806#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
807
808#La primera etapa del grub se fija en el primer disco duro
809FIRSTSTAGE=$(ogDiskToDev 1)
810
811#localizar disco segunda etapa del grub
812SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
813
814# prepara el directorio principal de la segunda etapa
815[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
816
817#Localizar directorio segunda etapa del grub   
818PREFIXSECONDSTAGE="/boot/grubMBR"
819
820# Instalamos grub para EFI en ESP
821if ogIsEfiActive; then
822    read EFIDISK EFIPART <<< $(ogGetEsp)
823    # Comprobamos que exista ESP y el directorio para ubuntu
824    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
825    if [ $? -ne 0 ]; then
826        ogFormat $EFIDISK $EFIPART FAT32
827        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
828    fi
829    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
830    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
831    EFIOPTGRUB=" --target x86_64-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
832else
833    EFIOPTGRUB=""
834fi
835
836# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
837if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
838then
839    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
840    then
841        # Si no se reconfigura se utiliza el grub.cfg orginal
842        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
843                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
844        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
845        # Reactivamos el grub con el grub.cfg original.
846        grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE} $FIRSTSTAGE
847        # Movemos el grubx64.efi
848        if ogIsEfiActive; then
849            mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
850            rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
851        fi
852        return $?
853    fi
854fi
855
856# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
857
858#llamada a updateBootCache para que aloje la primera fase del ogLive
859updateBootCache
860
861#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
862echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
863echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
864
865#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
866[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
867
868#Preparar configuración segunda etapa: crear ubicacion
869mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
870#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
871sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
872/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
873#Preparar configuración segunda etapa: crear entrada del sistema operativo
874grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
875
876#Instalar el grub
877grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
878
879# Movemos el grubx64.efi
880if ogIsEfiActive; then
881    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
882    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
883fi
884}
885
886
887#/**
888#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
889#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
890#@param   int_disk_SecondStage     
891#@param   int_part_SecondStage     
892#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
893#@param   str "kernel param "   
894#@return 
895#@exception OG_ERR_FORMAT    Formato incorrecto.
896#@version 1.0.2 - Primeras pruebas.
897#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
898#@date    2011-10-29
899#@version 1.0.3 - Soporte para linux de 32 y 64 bits
900#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
901#@date    2012-03-13
902#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
903#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
904#@date    2012-03-13
905#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
906#@author Irina Gomez, ETSII Universidad de Sevilla
907#@date    2019-01-08
908#*/ ##
909
910function ogGrubInstallPartition ()
911{
912
913# Variables locales.
914local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
915local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
916
917# Si se solicita, mostrar ayuda.
918if [ "$*" == "help" ]; then
919    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
920           "$FUNCNAME 1 1 FALSE " \
921           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
922    return
923fi 
924
925# Error si no se reciben 2 parámetros.
926[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
927
928DISK=$1; PART=$2;
929CHECKOS=${3:-"FALSE"}
930KERNELPARAM=$4
931BACKUPNAME=".backup.og"
932
933#error si no es linux.
934VERSION=$(ogGetOsVersion $DISK $PART)
935echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
936
937#Localizar primera etapa del grub
938FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
939
940#localizar disco segunda etapa del grub
941SECONDSTAGE=$(ogMount $DISK $PART)
942
943#Localizar directorio segunda etapa del grub   
944PREFIXSECONDSTAGE="/boot/grubPARTITION"
945
946# Si es EFI instalamos el grub en la ESP
947if ogIsEfiActive; then
948    read EFIDISK EFIPART <<< $(ogGetEsp)
949    # Comprobamos que exista ESP y el directorio para ubuntu
950    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
951    if [ $? -ne 0 ]; then
952        ogFormat $EFIDISK $EFIPART FAT32
953        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
954    fi
955    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
956    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
957    EFIOPTGRUB=" --target x86_64-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
958else
959    EFIOPTGRUB=""
960fi
961
962# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
963if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
964then
965    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
966    then
967        # Si no se reconfigura se utiliza el grub.cfg orginal
968        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
969                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
970        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
971        # Reactivamos el grub con el grub.cfg original.
972        grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE} $FIRSTSTAGE
973        # Movemos el grubx64.efi
974        if ogIsEfiActive; then
975            mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
976            rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
977        fi
978        return $?
979    fi
980fi
981
982# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
983#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
984echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
985echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
986
987#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
988[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
989
990#Preparar configuración segunda etapa: crear ubicacion
991mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
992#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
993sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
994/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
995#Preparar configuración segunda etapa: crear entrada del sistema operativo
996grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
997
998#Instalar el grub
999grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
1000
1001# Movemos el grubx64.efi
1002if ogIsEfiActive; then
1003    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
1004    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
1005fi
1006}
1007
1008
1009#/**
1010#         ogConfigureFstab int_ndisk int_nfilesys
1011#@brief   Configura el fstab según particiones existentes
1012#@param   int_ndisk      nº de orden del disco
1013#@param   int_nfilesys   nº de orden del sistema de archivos
1014#@return  (nada)
1015#@exception OG_ERR_FORMAT    Formato incorrecto.
1016#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
1017#@warning Puede haber un error si hay más de 1 partición swap.
1018#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
1019#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1020#@date    2013-03-21
1021#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
1022#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1023#@date    2016-11-03
1024#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
1025#@author  Irina Gómez, ETSII Universidad de Sevilla
1026#@date    2018-12-13
1027#*/ ##
1028function ogConfigureFstab ()
1029{
1030# Variables locales.
1031local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
1032local EFIDISK EFIPART EFIDEV EFIOPT
1033
1034# Si se solicita, mostrar ayuda.
1035if [ "$*" == "help" ]; then
1036    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1037           "$FUNCNAME 1 1"
1038    return
1039fi
1040# Error si no se reciben 2 parámetros.
1041[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1042# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
1043FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
1044[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
1045
1046# Hacer copia de seguridad del fichero fstab original.
1047cp -a ${FSTAB} ${FSTAB}.backup
1048# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
1049DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
1050PARTROOT=$(ogDiskToDev $1 $2)
1051# Configuración de swap (solo 1ª partición detectada).
1052PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
1053if [ -n "$PARTSWAP" ]
1054then
1055    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
1056    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
1057    if [ -n "$DEFSWAP" ]
1058    then
1059        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
1060        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1061    else
1062        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
1063        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1064        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
1065    fi 
1066else
1067    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
1068    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
1069fi
1070# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
1071if [ ogIsEfiActive ]; then
1072    read EFIDISK EFIPART <<< $(ogGetEsp)
1073    EFIDEV=$(ogDiskToDev $EFIDISK $EFIPART)
1074
1075    # Opciones de la partición ESP: si no existe ponemos un valor por defecto
1076    EFIOPT=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
1077    [ "$EFIOPT" == "" ] && EFIOPT='vfat\tumask=0077\t0\t1'
1078
1079    sed -i /"boot\/efi"/d  ${FSTAB}
1080    echo -e "$EFIDEV\t/boot/efi\t$EFIOPT" >> ${FSTAB}
1081fi
1082}
1083
1084#/**
1085#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
1086#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
1087#@param   int_ndisk      nº de orden del disco
1088#@param   int_nfilesys   nº de orden del sistema de archivos
1089#@param   str_name       nombre asignado (opcional)
1090#@return  (nada)
1091#@exception OG_ERR_FORMAT    Formato incorrecto.
1092#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1093#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1094#@note    Si no se indica nombre, se asigna un valor por defecto.
1095#@version 1.0.5 - Primera versión para OpenGnSys.
1096#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1097#@date    2013-03-21
1098#*/ ##
1099function ogSetLinuxName ()
1100{
1101# Variables locales.
1102local MNTDIR ETC NAME
1103
1104# Si se solicita, mostrar ayuda.
1105if [ "$*" == "help" ]; then
1106    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
1107           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
1108    return
1109fi
1110# Error si no se reciben 2 o 3 parámetros.
1111case $# in
1112    2)   # Asignar nombre automático (por defecto, "pc").
1113         NAME="$(ogGetHostname)"
1114         NAME=${NAME:-"pc"} ;;
1115    3)   # Asignar nombre del 3er parámetro.
1116         NAME="$3" ;;
1117    *)   # Formato de ejecución incorrecto.
1118         ogRaiseError $OG_ERR_FORMAT
1119         return $?
1120esac
1121
1122# Montar el sistema de archivos.
1123MNTDIR=$(ogMount $1 $2) || return $?
1124
1125ETC=$(ogGetPath $1 $2 /etc)
1126
1127if [ -d "$ETC" ]; then
1128        #cambio de nombre en hostname
1129        echo "$NAME" > $ETC/hostname
1130        #Opcion A para cambio de nombre en hosts
1131        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
1132        #Opcion B componer fichero de hosts
1133        cat > $ETC/hosts <<EOF
1134127.0.0.1       localhost
1135127.0.1.1       $NAME
1136
1137# The following lines are desirable for IPv6 capable hosts
1138::1     ip6-localhost ip6-loopback
1139fe00::0 ip6-localnet
1140ff00::0 ip6-mcastprefix
1141ff02::1 ip6-allnodes
1142ff02::2 ip6-allrouters
1143EOF
1144fi
1145}
1146
1147
1148
1149#/**
1150#         ogCleanLinuxDevices int_ndisk int_nfilesys
1151#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
1152#@param   int_ndisk      nº de orden del disco
1153#@param   int_nfilesys   nº de orden del sistema de archivos
1154#@return  (nada)
1155#@exception OG_ERR_FORMAT    Formato incorrecto.
1156#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1157#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1158#@version 1.0.5 - Primera versión para OpenGnSys.
1159#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1160#@date    2013-03-21
1161#@version 1.0.6b - Elimina fichero resume de hibernacion
1162#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1163#@date    2016-11-07
1164#*/ ##
1165function ogCleanLinuxDevices ()
1166{
1167# Variables locales.
1168local MNTDIR
1169
1170# Si se solicita, mostrar ayuda.
1171if [ "$*" == "help" ]; then
1172    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1173           "$FUNCNAME 1 1"
1174    return
1175fi
1176# Error si no se reciben 2 parámetros.
1177[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1178
1179# Montar el sistema de archivos.
1180MNTDIR=$(ogMount $1 $2) || return $?
1181
1182# Eliminar fichero de configuración de udev para dispositivos fijos de red.
1183[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
1184# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
1185[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
1186}
1187
1188#/**
1189# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
1190#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1191#@param 1 Numero de disco
1192#@param 2 Numero de particion
1193#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1194#@param 4 offline  configura el modo offline [offline|online] (opcional)
1195#@return  (nada)
1196#@exception OG_ERR_FORMAT    Formato incorrecto.
1197#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1198#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1199# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
1200#@version 1.0.6 - Prmera integración
1201#@author 
1202#@date    2016-11-07
1203#@version 1.1.0 - Se renombra funcion para adaptacion al cambio de nombre de ogclient a ogLive. Soporta varios ogLives en la cache. Se añade el ogLive asignado al cliente.
1204#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1205#@date    2017-06-17
1206#*/ ##
1207
1208
1209function ogGrubAddOgLive ()
1210{
1211    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
1212
1213    # Si se solicita, mostrar ayuda.
1214    if [ "$*" == "help" ]; then
1215        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1216                "$FUNCNAME 1 1" \
1217                "$FUNCNAME 1 6 15 offline"
1218        return
1219    fi
1220
1221    # Error si no se reciben 2 parámetros.
1222    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
1223    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
1224
1225    # Error si no existe el kernel y el initrd en la cache.
1226    # Falta crear nuevo codigo de error.
1227    [ -r $OGCAC/boot/${oglivedir}/ogvmlinuz -a -r $OGCAC/boot/${oglivedir}/oginitrd.img ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "CACHE: ogvmlinuz, oginitrd.img" 1>&2; echo $?)
1228
1229    # Archivo de configuracion del grub
1230    DIRMOUNT=$(ogMount $1 $2)
1231    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1232
1233    # Error si no existe archivo del grub
1234    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1235
1236    # Si existe la entrada de opengnsys, se borra
1237    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
1238
1239    # Tipo de tabla de particiones
1240    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1241
1242    # Localizacion de la cache
1243    read NUMDISK NUMPART <<< $(ogFindCache)
1244    let NUMDISK=$NUMDISK-1
1245    # kernel y sus opciones. Pasamos a modo usuario
1246    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
1247
1248    # Configuracion offline si existe parametro
1249    echo "$@" |grep offline &>/dev/null && STATUS=offline
1250    echo "$@" |grep online  &>/dev/null && STATUS=online
1251    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1252
1253    # Numero de línea de la primera entrada del grub.
1254    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1255    # Texto de la entrada de opengnsys
1256MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
1257\tinsmod part_$PARTTABLETYPE \n \
1258\tinsmod ext2 \n \
1259\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1260\tlinux $KERNEL \n \
1261\tinitrd /boot/${oglivedir}/oginitrd.img \n \
1262}"
1263
1264
1265    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1266    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1267
1268    # Ponemos que la entrada por defecto sea la primera.
1269    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1270
1271    # Si me dan valor para timeout lo cambio en el grub.
1272    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1273}
1274
1275#/**
1276# ogGrubHidePartitions num_disk num_part
1277#@brief ver ogBootLoaderHidePartitions
1278#@see ogBootLoaderHidePartitions
1279#*/ ##
1280function ogGrubHidePartitions ()
1281{
1282    # Si se solicita, mostrar ayuda.
1283    if [ "$*" == "help" ]; then
1284        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1285               "$FUNCNAME 1 6"
1286        return
1287    fi
1288    ogBootLoaderHidePartitions $@
1289    return $?
1290}
1291
1292#/**
1293# ogBurgHidePartitions num_disk num_part
1294#@brief ver ogBootLoaderHidePartitions
1295#@see ogBootLoaderHidePartitions
1296#*/ ##
1297function ogBurgHidePartitions ()
1298{
1299    # Si se solicita, mostrar ayuda.
1300    if [ "$*" == "help" ]; then
1301        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1302               "$FUNCNAME 1 6"
1303        return
1304    fi
1305    ogBootLoaderHidePartitions $@
1306    return $?
1307}
1308
1309#/**
1310# ogBootLoaderHidePartitions num_disk num_part
1311#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
1312#@param 1 Numero de disco
1313#@param 2 Numero de particion
1314#@return  (nada)
1315#@exception OG_ERR_FORMAT    Formato incorrecto.
1316#@exception No existe archivo de configuracion del grub/burg.
1317#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1318#@author  Irina Gomez, ETSII Universidad de Sevilla
1319#@date    2015-11-17
1320#@version 1.1 Se generaliza la función para grub y burg
1321#@author  Irina Gomez, ETSII Universidad de Sevilla
1322#@date    2017-10-20
1323#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1324#@author  Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
1325#@date    2018-07-05
1326#*/
1327
1328function ogBootLoaderHidePartitions ()
1329{
1330    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1331
1332    # Si se solicita, mostrar ayuda.
1333    if [ "$*" == "help" ]; then
1334        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
1335        return
1336    fi
1337
1338    # Nombre de la función que llama a esta.
1339    FUNC="${FUNCNAME[@]:1}"
1340    FUNC="${FUNC%%\ *}"
1341
1342    # Error si no se reciben 2 parámetros.
1343    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1344
1345    # Archivo de configuracion del grub
1346    DIRMOUNT=$(ogMount $1 $2)
1347    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1348    case "$FUNC" in
1349        ogGrubHidePartitions)
1350            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1351            ;;
1352        ogBurgHidePartitions)
1353            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1354            ;;
1355        *)
1356            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1357            return $?
1358            ;;
1359    esac
1360
1361    # Error si no existe archivo del grub
1362    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
1363
1364    # Si solo hay una particion de Windows me salgo
1365    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
1366
1367    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
1368    sed -i '/parttool/d' $CFGFILE
1369
1370    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1371#   /*  (comentario de bloque para  Doxygen)
1372    # Entradas de Windows: numero de linea y particion. De mayor a menor.
1373    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
1374    #*/ (comentario para bloque Doxygen)
1375    # Particiones de Windows, pueden no estar en el grub.
1376    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
1377    # Modifico todas las entradas de Windows.
1378    for ENTRY in $WINENTRY; do
1379        LINE=${ENTRY%:*}
1380        PART=${ENTRY#*:}
1381        # En cada entrada, oculto o muestro cada particion.
1382        TEXT=""
1383        for PART2 in $WINPART; do
1384                # Muestro solo la particion de la entrada actual.
1385                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
1386
1387                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
1388        done
1389       
1390        sed -i "${LINE}a\ $TEXT" $CFGFILE
1391    done
1392
1393    # Activamos la particion que se inicia en todas las entradas de windows.
1394    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
1395
1396}
1397
1398#/**
1399# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
1400#@brief ver ogBootLoaderDeleteEntry
1401#@see ogBootLoaderDeleteEntry
1402#*/
1403function ogGrubDeleteEntry ()
1404{
1405    # Si se solicita, mostrar ayuda.
1406    if [ "$*" == "help" ]; then
1407        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1408                "$FUNCNAME 1 6 2 1"
1409        return
1410    fi
1411    ogBootLoaderDeleteEntry $@
1412    return $?
1413}
1414
1415#/**
1416# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
1417#@brief ver ogBootLoaderDeleteEntry
1418#@see ogBootLoaderDeleteEntry
1419#*/
1420function ogBurgDeleteEntry ()
1421{
1422    # Si se solicita, mostrar ayuda.
1423    if [ "$*" == "help" ]; then
1424        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1425                "$FUNCNAME 1 6 2 1"
1426        return
1427    fi
1428    ogBootLoaderDeleteEntry $@
1429    return $?
1430}
1431
1432#/**
1433# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1434#@brief Borra en el grub las entradas para el inicio en una particion.
1435#@param 1 Numero de disco donde esta el grub
1436#@param 2 Numero de particion donde esta el grub
1437#@param 3 Numero del disco del que borramos las entradas
1438#@param 4 Numero de la particion de la que borramos las entradas
1439#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
1440#@return  (nada)
1441#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1442#@exception OG_ERR_FORMAT    Formato incorrecto.
1443#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1444#@version 1.1 Se generaliza la función para grub y burg
1445#@author  Irina Gomez, ETSII Universidad de Sevilla
1446#@date    2017-10-20
1447#*/ ##
1448
1449function ogBootLoaderDeleteEntry ()
1450{
1451    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
1452
1453    # Si se solicita, mostrar ayuda.
1454    if [ "$*" == "help" ]; then
1455        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1456        return
1457    fi
1458
1459    # Si el número de parámetros menos que 4 nos salimos
1460    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1461 
1462
1463    # Nombre de la función que llama a esta.
1464    FUNC="${FUNCNAME[@]:1}"
1465    FUNC="${FUNC%%\ *}"
1466
1467    # Archivo de configuracion del grub
1468    DIRMOUNT=$(ogMount $1 $2)
1469    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1470    case "$FUNC" in
1471        ogGrubDeleteEntry)
1472            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1473            ;;
1474        ogBurgDeleteEntry)
1475            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1476            ;;
1477        *)
1478            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1479            return $?
1480            ;;
1481    esac
1482
1483    # Dispositivo
1484    DEVICE=$(ogDiskToDev $3 $4)
1485
1486    # Error si no existe archivo del grub)
1487    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
1488
1489    # Numero de linea de cada entrada.
1490    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1491
1492    # Entradas que hay que borrar.
1493    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1494
1495    # Si no hay entradas para borrar me salgo con aviso
1496    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
1497
1498    # Recorremos el fichero del final hacia el principio.
1499    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1500    for ENTRY in $MENUENTRY; do
1501        # Comprobamos si hay que borrar la entrada.
1502        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1503            let ENDENTRY=$ENDENTRY-1
1504            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1505        fi
1506
1507        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1508        ENDENTRY=$ENTRY
1509    done
1510}
1511
1512#/**
1513#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1514#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1515#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1516#@param   int_disk_SecondStage     
1517#@param   int_part_SecondStage     
1518#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1519#@return 
1520#@exception OG_ERR_FORMAT    Formato incorrecto.
1521#@exception OG_ERR_PARTITION  Partición no soportada
1522#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1523#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1524#@date    2017-06-23
1525#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1526#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1527#@date    2018-01-21
1528#@version 1.1.0 - Refactorizar fichero de configuacion
1529#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1530#@date    2018-01-24
1531#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1532#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1533#@date    2018-07-05
1534#*/ ##
1535
1536function ogBurgInstallMbr ()
1537{
1538 
1539# Variables locales.
1540local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1541
1542# Si se solicita, mostrar ayuda.
1543if [ "$*" == "help" ]; then
1544    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1545           "$FUNCNAME 1 1 FALSE " \
1546           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1547    return
1548fi 
1549
1550# Error si no se reciben 2 parametros.
1551[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1552
1553
1554DISK=$1; PART=$2;
1555CHECKOS=${3:-"FALSE"}
1556KERNELPARAM=$4
1557BACKUPNAME=".backup.og"
1558
1559#Error si no es linux.
1560ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1561
1562
1563#La primera etapa del grub se fija en el primer disco duro
1564FIRSTSTAGE=$(ogDiskToDev 1)
1565
1566#localizar disco segunda etapa del grub
1567SECONDSTAGE=$(ogMount $DISK $PART)
1568
1569# prepara el directorio principal de la segunda etapa (y copia los binarios)
1570[ -d ${SECONDSTAGE}/boot/burg/ ]  || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/*  ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/*  ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; #*/ ## (comentario Dogygen) #*/ ## (comentario Dogygen)
1571
1572#Copiamos el tema
1573mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1574cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
1575
1576#Localizar directorio segunda etapa del grub   
1577#PREFIXSECONDSTAGE="/boot/burg/"
1578
1579# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1580if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1581then
1582    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1583    then
1584        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1585        return $?
1586    fi
1587fi
1588
1589# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1590
1591#llamada a updateBootCache para que aloje la primera fase del ogLive
1592updateBootCache
1593
1594#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1595echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1596echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1597
1598
1599#Preparar configuración segunda etapa: crear ubicacion
1600mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1601
1602#Preparar configuración segunda etapa: crear cabecera del fichero
1603#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1604
1605FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1606
1607#/* ## (comentario Dogygen)
1608cat > "$FILECFG" << EOF
1609
1610set theme_name=OpenGnsys
1611set gfxmode=1024x768
1612
1613
1614set locale_dir=(\$root)/boot/burg/locale
1615
1616set default=0
1617set timeout=25
1618set lang=es
1619
1620
1621insmod ext2
1622insmod gettext
1623
1624
1625
1626
1627if [ -s \$prefix/burgenv ]; then
1628  load_env
1629fi
1630
1631
1632
1633if [ \${prev_saved_entry} ]; then
1634  set saved_entry=\${prev_saved_entry}
1635  save_env saved_entry
1636  set prev_saved_entry=
1637  save_env prev_saved_entry
1638  set boot_once=true
1639fi
1640
1641function savedefault {
1642  if [ -z \${boot_once} ]; then
1643    saved_entry=\${chosen}
1644    save_env saved_entry
1645  fi
1646}
1647function select_menu {
1648  if menu_popup -t template_popup theme_menu ; then
1649    free_config template_popup template_subitem menu class screen
1650    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1651    save_env theme_name
1652    menu_refresh
1653  fi
1654}
1655
1656function toggle_fold {
1657  if test -z $theme_fold ; then
1658    set theme_fold=1
1659  else
1660    set theme_fold=
1661  fi
1662  save_env theme_fold
1663  menu_refresh
1664}
1665function select_resolution {
1666  if menu_popup -t template_popup resolution_menu ; then
1667    menu_reload_mode
1668    save_env gfxmode
1669  fi
1670}
1671
1672
1673if test -f \${prefix}/themes/\${theme_name}/theme ; then
1674  insmod coreui
1675  menu_region.text
1676  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1677  load_config \${prefix}/themes/conf.d/10_hotkey   
1678  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1679  insmod vbe
1680  insmod png
1681  insmod jpeg
1682  set gfxfont="Unifont Regular 16"
1683  menu_region.gfx
1684  vmenu resolution_menu
1685  controller.ext
1686fi
1687
1688
1689EOF
1690#*/ ## (comentario Dogygen)
1691
1692#Preparar configuración segunda etapa: crear entrada del sistema operativo
1693grubSyntax "$KERNELPARAM" >> "$FILECFG"
1694
1695
1696#Instalar el burg
1697burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1698}
1699
1700#/**
1701# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1702#@brief ver ogBootLoaderDefaultEntry
1703#@see ogBootLoaderDefaultEntry
1704#*/ ##
1705function ogGrubDefaultEntry ()
1706{
1707    # Si se solicita, mostrar ayuda.
1708    if [ "$*" == "help" ]; then
1709        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1710               "$FUNCNAME 1 6 1 1"
1711        return
1712    fi
1713    ogBootLoaderDefaultEntry $@
1714    return $?
1715}
1716
1717#/**
1718# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1719#@brief ver ogBootLoaderDefaultEntry
1720#@see ogBootLoaderDefaultEntry
1721#*/ ##
1722function ogBurgDefaultEntry ()
1723{
1724    # Si se solicita, mostrar ayuda.
1725    if [ "$*" == "help" ]; then
1726        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1727               "$FUNCNAME 1 6 1 1"
1728        return
1729    fi
1730    ogBootLoaderDefaultEntry $@
1731    return $?
1732}
1733
1734#/**
1735# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1736#@brief   Configura la entrada por defecto de Burg
1737#@param   int_disk_SecondStage     
1738#@param   int_part_SecondStage     
1739#@param   int_disk_default_entry
1740#@param   int_part_default_entry
1741#@return 
1742#@exception OG_ERR_FORMAT    Formato incorrecto.
1743#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1744#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1745#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1746#@version 1.1.0 - Define la entrada por defecto del Burg
1747#@author  Irina Gomez, ETSII Universidad de Sevilla
1748#@date    2017-08-09
1749#@version 1.1 Se generaliza la función para grub y burg
1750#@author  Irina Gomez, ETSII Universidad de Sevilla
1751#@date    2018-01-04
1752#*/ ##
1753function ogBootLoaderDefaultEntry ()
1754{
1755
1756# Variables locales.
1757local PART CFGFILE DEFAULTENTRY MSG
1758
1759# Si se solicita, mostrar ayuda.
1760if [ "$*" == "help" ]; then
1761    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
1762    return
1763fi 
1764
1765# Nombre de la función que llama a esta.
1766FUNC="${FUNCNAME[@]:1}"
1767FUNC="${FUNC%%\ *}"
1768
1769# Error si no se reciben 3 parametros.
1770[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1771
1772# Error si no puede montar sistema de archivos.
1773DIRMOUNT=$(ogMount $1 $2) || return $?
1774
1775# Comprobamos que exista fichero de configuración
1776# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1777case "$FUNC" in
1778    ogGrubDefaultEntry)
1779        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1780        ;;
1781    ogBurgDefaultEntry)
1782        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1783        ;;
1784    *)
1785        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1786        return $?
1787        ;;
1788esac
1789
1790# Error si no existe archivo de configuración
1791[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1792
1793# Dispositivo
1794DEVICE=$(ogDiskToDev $3 $4)
1795
1796# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1797DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1798
1799# Si no hay entradas para borrar me salgo con aviso
1800[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
1801
1802# Número de la de linea por defecto en el menú de usuario
1803MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1804# Las líneas empiezan a contar desde cero
1805let MENUENTRY=$MENUENTRY-1
1806sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1807MSG="MSG_HELP_$FUNC"
1808echo "${!MSG%%\.}: $@"
1809}
1810
1811#/**
1812# ogGrubOgliveDefaultEntry num_disk num_part
1813#@brief ver ogBootLoaderOgliveDefaultEntry
1814#@see ogBootLoaderOgliveDefaultEntry
1815#*/ ##
1816function ogGrubOgliveDefaultEntry ()
1817{
1818    # Si se solicita, mostrar ayuda.
1819    if [ "$*" == "help" ]; then
1820        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1821               "$FUNCNAME 1 6"
1822        return
1823    fi
1824    ogBootLoaderOgliveDefaultEntry $@
1825    return $?
1826}
1827
1828#/**
1829# ogBurgOgliveDefaultEntry num_disk num_part
1830#@brief ver ogBootLoaderOgliveDefaultEntry
1831#@see ogBootLoaderOgliveDefaultEntry
1832#*/ ##
1833function ogBurgOgliveDefaultEntry ()
1834{
1835    # Si se solicita, mostrar ayuda.
1836    if [ "$*" == "help" ]; then
1837        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1838               "$FUNCNAME 1 6"
1839        return
1840    fi
1841    ogBootLoaderOgliveDefaultEntry $@
1842    return $?
1843}
1844
1845#/**
1846# ogBootLoaderOgliveDefaultEntry
1847#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1848#@param   int_disk_SecondStage     
1849#@param   int_part_SecondStage     
1850#@return 
1851#@exception OG_ERR_FORMAT    Formato incorrecto.
1852#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1853#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1854#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1855#@version 1.1.0 - Primeras pruebas con Burg
1856#@author  Irina Gomez, ETSII Universidad de Sevilla
1857#@date    2017-08-09
1858#@version 1.1 Se generaliza la función para grub y burg
1859#@author  Irina Gomez, ETSII Universidad de Sevilla
1860#@date    2018-01-04
1861#*/ ##
1862function  ogBootLoaderOgliveDefaultEntry ()
1863{
1864
1865# Variables locales.
1866local FUNC PART CFGFILE NUMENTRY MSG
1867
1868# Si se solicita, mostrar ayuda.
1869if [ "$*" == "help" ]; then
1870    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
1871    return
1872fi 
1873
1874# Nombre de la función que llama a esta.
1875FUNC="${FUNCNAME[@]:1}"
1876FUNC="${FUNC%%\ *}"
1877
1878# Error si no se reciben 2 parametros.
1879[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1880
1881# Error si no puede montar sistema de archivos.
1882PART=$(ogMount $1 $2) || return $?
1883# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1884case "$FUNC" in
1885    ogGrubOgliveDefaultEntry)
1886        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1887        ;;
1888    ogBurgOgliveDefaultEntry)
1889        CFGFILE="$PART/boot/burg/burg.cfg"
1890        ;;
1891    *)
1892        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1893        return $?
1894        ;;
1895esac
1896
1897# Comprobamos que exista fichero de configuración
1898[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1899
1900# Detectamos cual es la entrada de ogLive
1901NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
1902
1903# Si no existe entrada de ogLive nos salimos
1904[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
1905
1906let NUMENTRY=$NUMENTRY-1
1907sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
1908
1909MSG="MSG_HELP_$FUNC"
1910echo "${!MSG%%\.}: $@"
1911}
1912
1913
1914#/**
1915# ogGrubSetTheme num_disk num_part str_theme
1916#@brief ver ogBootLoaderSetTheme
1917#@see ogBootLoaderSetTheme
1918#*/ ##
1919function ogGrubSetTheme ()
1920{
1921    # Si se solicita, mostrar ayuda.
1922    if [ "$*" == "help" ]; then
1923        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1924               "$FUNCNAME 1 4 ThemeBasic"\
1925               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1926        return
1927    fi
1928    ogBootLoaderSetTheme $@
1929    return $?
1930}
1931
1932#/**
1933# ogBurgSetTheme num_disk num_part str_theme
1934#@brief ver ogBootLoaderSetTheme
1935#@see ogBootLoaderSetTheme
1936#*/ ##
1937function ogBurgSetTheme  ()
1938{
1939    # Si se solicita, mostrar ayuda.
1940    if [ "$*" == "help" ]; then
1941        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1942               "$FUNCNAME 1 4 ThemeBasic" \
1943               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1944        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
1945               
1946        return
1947    fi
1948    ogBootLoaderSetTheme $@
1949    return $?
1950}
1951
1952
1953
1954#/**
1955# ogBootLoaderSetTheme
1956#@brief   asigna un tema al BURG
1957#@param   int_disk_SecondStage     
1958#@param   int_part_SecondStage 
1959#@param   str_theme_name   
1960#@return 
1961#@exception OG_ERR_FORMAT    Formato incorrecto.
1962#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1963#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
1964#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
1965#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
1966#@author  Antonio J. Doblas Viso. Universidad de Malaga
1967#@date    2018-01-24
1968#*/ ##
1969function  ogBootLoaderSetTheme ()
1970{
1971
1972# Variables locales.
1973local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG
1974
1975# Si se solicita, mostrar ayuda.
1976if [ "$*" == "help" ]; then
1977    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme"
1978    return   
1979fi
1980 
1981
1982NEWTHEME="$3"
1983
1984# Nombre de la función que llama a esta.
1985FUNC="${FUNCNAME[@]:1}"
1986FUNC="${FUNC%%\ *}"
1987
1988
1989
1990# Error si no se reciben 2 parametros.
1991[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
1992
1993# Error si no puede montar sistema de archivos.
1994PART=$(ogMount $1 $2) || return $?
1995# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme.
1996case "$FUNC" in
1997    ogGrubSetTheme)
1998        BOOTLOADER="grug"
1999        BOOTLOADERDIR="grubMBR"
2000        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2001        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
2002        return $?               
2003        ;;
2004    ogBurgSetTheme)
2005        BOOTLOADER="burg"
2006        BOOTLOADERDIR="burg"
2007        CFGFILE="$PART/boot/burg/burg.cfg"       
2008        ;;
2009    *)
2010        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme or ogBurgSetTheme."
2011        return $?
2012        ;;
2013esac
2014
2015# Comprobamos que exista fichero de configuración
2016[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2017
2018# Detectamos cual es el tema asignado
2019THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
2020
2021# Si no existe entrada de theme_name  nos salimos
2022[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
2023
2024#Actualizamos el tema del servidor a la particion
2025if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
2026        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/boot/$BOOTLOADERDIR/themes/   
2027fi
2028
2029#Verificamos que el tema esta en la particion
2030if ! [ -d $PART/boot/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
2031                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/boot/$BOOTLOADERDIR/themes/" || return $?
2032fi
2033
2034#Cambiamos la entrada el fichero de configuración.
2035sed --regexp-extended -i  s/"$THEME"/"$NEWTHEME"/g $CFGFILE
2036
2037
2038}
2039
2040#/**
2041# ogGrubSetAdminKeys num_disk num_part str_theme
2042#@brief ver ogBootLoaderSetTheme
2043#@see ogBootLoaderSetTheme
2044#*/ ##
2045function ogGrubSetAdminKeys ()
2046{
2047    # Si se solicita, mostrar ayuda.
2048    if [ "$*" == "help" ]; then
2049        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2050               "$FUNCNAME 1 4 FALSE "\
2051               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2052        return
2053    fi
2054    ogBootLoaderSetAdminKeys $@
2055    return $?
2056}
2057
2058#/**
2059# ogBurgSetAdminKeys num_disk num_part str_bolean
2060#@brief ver ogBootLoaderSetAdminKeys
2061#@see ogBootLoaderSetAdminKeys
2062#*/ ##
2063function ogBurgSetAdminKeys  ()
2064{
2065    # Si se solicita, mostrar ayuda.
2066    if [ "$*" == "help" ]; then
2067        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2068               "$FUNCNAME 1 4 TRUE" \
2069               "$FUNCNAME \$(ogFindCache) FALSE"               
2070        return
2071    fi
2072    ogBootLoaderSetAdminKeys $@
2073    return $?
2074}
2075
2076
2077
2078#/**
2079# ogBootLoaderSetAdminKeys
2080#@brief   Activa/Desactica las teclas de administracion
2081#@param   int_disk_SecondStage     
2082#@param   int_part_SecondStage 
2083#@param   Boolean TRUE/FALSE   
2084#@return 
2085#@exception OG_ERR_FORMAT    Formato incorrecto.
2086#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2087#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2088#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2089#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2090#@author  Antonio J. Doblas Viso. Universidad de Malaga
2091#@date    2018-01-24
2092#*/ ##
2093function  ogBootLoaderSetAdminKeys ()
2094{
2095
2096# Variables locales.
2097local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2098
2099# Si se solicita, mostrar ayuda.
2100if [ "$*" == "help" ]; then
2101    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2102    return   
2103fi
2104 
2105
2106# Nombre de la función que llama a esta.
2107FUNC="${FUNCNAME[@]:1}"
2108FUNC="${FUNC%%\ *}"
2109
2110
2111# Error si no se reciben 2 parametros.
2112[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2113
2114# Error si no puede montar sistema de archivos.
2115PART=$(ogMount $1 $2) || return $?
2116# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2117case "$FUNC" in
2118    ogGrubSetAdminKeys)
2119        BOOTLOADER="grug"
2120        BOOTLOADERDIR="grubMBR"
2121        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2122        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2123        return $?       
2124        ;;
2125    ogBurgSetAdminKeys)
2126        BOOTLOADER="burg"
2127        BOOTLOADERDIR="burg"
2128        CFGFILE="$PART/boot/burg/burg.cfg"       
2129        ;;
2130    *)
2131        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2132        return $?
2133        ;;
2134esac
2135
2136
2137# Comprobamos que exista fichero de configuración
2138[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2139
2140
2141case "$3" in
2142        true|TRUE)
2143                [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey
2144        ;;
2145        false|FALSE)
2146                [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled
2147        ;;     
2148        *)
2149           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2150        return $?
2151    ;; 
2152esac
2153}
2154
2155
2156
2157#/**
2158# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
2159#@brief ver ogBootLoaderSetTimeOut
2160#@see ogBootLoaderSetTimeOut
2161#*/ ##
2162function ogGrubSetTimeOut ()
2163{
2164    # Si se solicita, mostrar ayuda.
2165    if [ "$*" == "help" ]; then
2166        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2167               "$FUNCNAME 1 4 50 "\
2168               "$FUNCNAME \$(ogFindCache) 50"
2169        return
2170    fi
2171    ogBootLoaderSetTimeOut $@
2172    return $?
2173}
2174
2175#/**
2176# ogBurgSetTimeOut num_disk num_part str_bolean
2177#@brief ver ogBootLoaderSetTimeOut
2178#@see ogBootLoaderSetTimeOut
2179#*/ ##
2180function ogBurgSetTimeOut ()
2181{
2182    # Si se solicita, mostrar ayuda.
2183    if [ "$*" == "help" ]; then
2184        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2185               "$FUNCNAME 1 4 50" \
2186               "$FUNCNAME \$(ogFindCache) 50"               
2187        return
2188    fi
2189    ogBootLoaderSetTimeOut $@
2190    return $?
2191}
2192
2193
2194
2195#/**
2196# ogBootLoaderSetTimeOut
2197#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2198#@param   int_disk_SecondStage     
2199#@param   int_part_SecondStage 
2200#@param   int_timeout_seconds   
2201#@return 
2202#@exception OG_ERR_FORMAT    Formato incorrecto.
2203#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2204#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2205#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2206#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2207#@author  Antonio J. Doblas Viso. Universidad de Malaga
2208#@date    2018-01-24
2209#*/ ##
2210function  ogBootLoaderSetTimeOut ()
2211{
2212
2213# Variables locales.
2214local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2215
2216# Si se solicita, mostrar ayuda.
2217if [ "$*" == "help" ]; then
2218    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut"
2219    return   
2220fi
2221 
2222ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2223
2224# Nombre de la función que llama a esta.
2225FUNC="${FUNCNAME[@]:1}"
2226FUNC="${FUNC%%\ *}"
2227
2228# Error si no se reciben 3 parametros.
2229[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2230
2231# Error si no puede montar sistema de archivos.
2232PART=$(ogMount $1 $2) || return $?
2233# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut.
2234case "$FUNC" in
2235    ogGrubSetTimeOut)
2236        BOOTLOADER="grug"
2237        BOOTLOADERDIR="grubMBR"
2238        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2239        ;;
2240    ogBurgSetTimeOut)
2241        BOOTLOADER="burg"
2242        BOOTLOADERDIR="burg"
2243        CFGFILE="$PART/boot/burg/burg.cfg"       
2244        ;;
2245    *)
2246        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut"
2247        return $?
2248        ;;
2249esac
2250
2251# Comprobamos que exista fichero de configuración
2252[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2253
2254# Asignamos el timeOut.
2255sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2256}
2257
2258
2259#/**
2260# ogGrubSetResolution num_disk num_part int_resolution
2261#@brief ver ogBootLoaderSetResolution
2262#@see ogBootLoaderSetResolution
2263#*/ ##
2264function ogGrubSetResolution ()
2265{
2266    # Si se solicita, mostrar ayuda.
2267    if [ "$*" == "help" ]; then
2268        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2269             "$FUNCNAME 1 4 1024x768" \
2270             "$FUNCNAME \$(ogFindCache) 1024x768" \
2271             "$FUNCNAME 1 4" 
2272        return
2273    fi
2274    ogBootLoaderSetResolution $@
2275    return $?
2276}
2277
2278#/**
2279# ogBurgSetResolution num_disk num_part str_bolean
2280#@brief ver ogBootLoaderSetResolution
2281#@see ogBootLoaderSetResolution
2282#*/ ##
2283function ogBurgSetResolution ()
2284 {
2285    # Si se solicita, mostrar ayuda.
2286    if [ "$*" == "help" ]; then
2287        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2288               "$FUNCNAME 1 4 1024x768" \
2289               "$FUNCNAME \$(ogFindCache) 1024x768" \
2290               "$FUNCNAME 1 4"               
2291        return
2292    fi
2293    ogBootLoaderSetResolution $@
2294    return $?
2295}
2296
2297
2298
2299#/**
2300# ogBootLoaderSetResolution
2301#@brief   Define la resolucion que usuara el thema del gestor de arranque
2302#@param   int_disk_SecondStage     
2303#@param   int_part_SecondStage 
2304#@param   str_resolution (Opcional)   
2305#@return 
2306#@exception OG_ERR_FORMAT    Formato incorrecto.
2307#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2308#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2309#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2310#@author  Antonio J. Doblas Viso. Universidad de Malaga
2311#@date    2018-01-24
2312#*/ ##
2313function  ogBootLoaderSetResolution ()
2314{
2315
2316# Variables locales.
2317local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2318
2319# Si se solicita, mostrar ayuda.
2320if [ "$*" == "help" ]; then
2321    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution"
2322    return   
2323fi
2324
2325
2326# Nombre de la función que llama a esta.
2327FUNC="${FUNCNAME[@]:1}"
2328FUNC="${FUNC%%\ *}"
2329
2330
2331# Error si no se reciben 2 parametros.
2332[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2333
2334# Error si no puede montar sistema de archivos.
2335PART=$(ogMount $1 $2) || return $?
2336# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution.
2337case "$FUNC" in
2338    ogGrubSetResolution)
2339        BOOTLOADER="grug"
2340        BOOTLOADERDIR="grubMBR"
2341        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2342        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2343        return $?     
2344        ;;
2345    ogBurgSetResolution)
2346        BOOTLOADER="burg"
2347        BOOTLOADERDIR="burg"
2348        CFGFILE="$PART/boot/burg/burg.cfg"       
2349        ;;
2350    *)
2351        ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution"
2352        return $?
2353        ;;
2354esac
2355
2356DEFAULTRESOLUTION=1024x768
2357
2358# Comprobamos que exista fichero de configuración
2359[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2360
2361#controlar variable a consierar vga (default template) o video (menu)
2362#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2363if [ $# -eq 2 ] ; then 
2364        if [ -n $video ]; then
2365                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2366        fi
2367        if [ -n $vga ] ; then
2368        case "$vga" in
2369                788|789|814)
2370                        NEWRESOLUTION=800x600
2371                        ;;
2372                791|792|824)
2373                        NEWRESOLUTION=1024x768
2374                        ;;
2375                355)
2376                        NEWRESOLUTION=1152x864
2377                        ;;
2378                794|795|829)
2379                        NEWRESOLUTION=1280x1024
2380                        ;;
2381        esac
2382        fi
2383fi
2384
2385if [ $# -eq 3 ] ; then
2386        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2387        ogCheckStringInReg $3 "[0-9]{3,4}[x][0-9]{3,4}\$" &&  NEWRESOLUTION="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a valid resolution: 800x600, 1024x768, 1152x864, 1280x1024, 1600x1200"
2388fi
2389
2390# Si no existe NEWRESOLUCION  asignamos la defaulT
2391[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2392
2393#Cambiamos la entrada el fichero de configuración.
2394sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2395}
2396
2397#/**
2398#         ogRefindInstall  int_ndisk bool_autoconfig
2399#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2400#@param   int_ndisk
2401#@param   bolean_Check__auto_config   true | false[default]
2402#@return
2403#@exception OG_ERR_FORMAT    Formato incorrecto.
2404#@version 1.1.0 - Primeras pruebas.
2405#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2406#@date    2017-06-26
2407#*/ ##
2408function ogRefindInstall ()
2409{
2410
2411# Variables locales.
2412local DISK EFIDIR CONFIG EFIPARTITIONID
2413
2414
2415# Si se solicita, mostrar ayuda.
2416if [ "$*" == "help" ]; then
2417    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk boolean_autoconfig " \
2418           "$FUNCNAME 1 TRUE"
2419    return
2420fi
2421
2422# Error si no se recibe 1 parámetro.
2423[ $# -ge 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
2424
2425
2426DISK=$1
2427EFIDIR=/mnt/$(ogDiskToDev $1 1 | cut -c 6-8)$1/EFI
2428CONFIG=${2:-"FALSE"}
2429EFIPARTITIONID=$(ogGetPartitionId $1 1)
2430if [ "$EFIPARTITIONID" == "EF00" ] || [ "$EFIPARTITIONID" == "ef00" ]; then
2431    cp -pr /opt/opengnsys/lib/refind ${EFIDIR}
2432    case "$CONFIG" in
2433        FALSE)
2434        if [ -a ${EFIDIR}/ubuntu ]; then
2435            echo "menuentry \"Ubuntu\" {" >> ${EFIDIR}/refind/refind.conf
2436            echo "loader /EFI/ubuntu/grubx64.efi" >> ${EFIDIR}/refind/refind.conf
2437            echo "icon /EFI/refind/icons/os_linux.png" >> ${EFIDIR}/refind/refind.conf
2438            echo "}" >> ${EFIDIR}/refind/refind.conf
2439        fi
2440        if [ -a ${EFIDIR}/Microsoft ]; then
2441            echo "menuentry \"Windows\" {" >> ${EFIDIR}/refind/refind.conf
2442            echo "loader /EFI/Microsoft/Boot/bootmgfw.efi" >> ${EFIDIR}/refind/refind.conf
2443            echo "}" >> ${EFIDIR}/refind/refind.conf
2444        fi
2445        ;;
2446        TRUE)
2447        cp  ${EFIDIR}/refind/refind.conf.auto ${EFIDIR}/refind/refind.conf
2448        ;;
2449    esac
2450else
2451$(ogRaiseError $OG_ERR_FORMAT; echo $?)
2452fi
2453}
2454
Note: See TracBrowser for help on using the repository browser.