source: client/engine/Boot.lib @ 5050850

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 5050850 was 527cd97, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #888 #890 ogNvramAddEntry function allows disk and partition as params and creates a entry with 'Part-D-P' name that uses generic loader of OpenGnsys. ogGrubInstall uses shimx64.efi.signed of ogLive Ubuntu 18. Previously this function used shim of tftp of server.

  • Property mode set to 100755
File size: 96.0 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#@version 1.1.1 - UEFI: Permite iniciar linux recien instalados (ticket #802 #890)
41#@author  Irina Gomez, ETSII Universidad de Sevilla
42#@date    2019-03-13
43#*/ ##
44function ogBoot ()
45{
46# Variables locales.
47local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
48local EFIDISK EFIPART EFIDIR BOOTLABEL BOOTLOADER BOOTNO DIRGRUB b
49
50# Si se solicita, mostrar ayuda.
51if [ "$*" == "help" ]; then
52    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_kernel str_initrd str_kernelparams]" \
53           "$FUNCNAME 1 1" "$FUNCNAME 1 2 \"/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro\""
54    return
55fi
56# Error si no se reciben 2 o 3 parámetros.
57[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
58
59# Detectar tipo de sistema de archivos y montarlo.
60PART=$(ogDiskToDev $1 $2) || return $?
61TYPE=$(ogGetOsType $1 $2) || return $?
62# Error si no puede montar sistema de archivos.
63MNTDIR=$(ogMount $1 $2) || return $?
64
65case "$TYPE" in
66    Linux|Android)
67        # Si no se indican, obtiene los parámetros de arranque para Linux.
68        PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}"
69        # Si no existe y el UEFI buscar en particion ESP
70        [ -z "$PARAMS" ] && ogIsEfiActive && PARAMS="$(ogLinuxBootParameters $(ogGetEsp))"
71        # Si no existe, buscar sistema de archivo /boot en /etc/fstab.
72        if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then
73            # Localizar S.F. /boot en /etc/fstab del S.F. actual.
74            PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
75            # Montar S.F. de /boot.
76            MNTDIR=$(ogMount $PART) || return $?
77            # Buscar los datos de arranque.
78            PARAMS=$(ogLinuxBootParameters $PART) || exit $?
79        fi
80        read -e KERNEL INITRD APPEND <<<"$PARAMS"
81        # Si no hay kernel, no hay sistema operativo.
82        [ -n "$KERNEL" -a -e "$MNTDIR/$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
83        # Arrancar de partición distinta a la original.
84        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
85        # Comprobar tipo de sistema.
86        if ogIsEfiActive; then
87            # Comprobar si el Kernel está firmado.
88            if ! file -k "$MNTDIR/$KERNEL" | grep -q "EFI app"; then
89                ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)"
90                return $?
91            fi
92
93            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
94            BOOTLOADER="shimx64.efi"
95            # Obtener parcición EFI.
96            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
97            # TODO: Comprobamos que existe la BOOTLABEL, si no buscamos por sistema operativo
98            if [ "$(ogGetPath $EFIDISK $EFIPART EFI/$BOOTLABEL)" == "" ]; then
99                OSVERSION="$(ogGetOsVersion $1 $2)"
100                case $OSVERSION in
101                    *SUSE*)
102                       BOOTLABEL="opensuse"
103                       ;;
104                    *Fedora*)
105                       BOOTLABEL="fedora"
106                       ;;
107                    *Ubuntu*)
108                       BOOTLABEL="ubuntu"
109                       ;;
110                    *)
111                       ogRaiseError $OG_ERR_NOTFOUND "$EFIDISK $EFIPART Boot loader"; return $?
112                       ;;
113                esac
114            fi
115
116            # Crear orden de arranque (con unos valores por defecto).
117            ogNvramAddEntry $BOOTLABEL "/EFI/$BOOTLABEL/Boot/$BOOTLOADER"
118            # Marcar próximo arranque y reiniciar.
119            ogNvramSetNext "$BOOTLABEL"
120            reboot
121        else
122            # Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB.
123            kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
124            kexec -e &
125        fi
126        ;;
127    Windows)
128        # Comprobar tipo de sistema.
129        if ogIsEfiActive; then
130            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
131            # Obtener parcición EFI.
132            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
133            [ -n "$EFIPART" ] || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
134            EFIDIR=$(ogMount $EFIDISK $EFIPART) || exit $?
135            # Comprobar cargador (si no existe buscar por defecto en ESP).
136            LOADER=$(ogGetPath $EFIDIR/EFI/$BOOTLABEL/Boot/bootmgfw.efi)
137            [ -z "$LOADER" ] && BOOTLABEL=Microsoft && LOADER=$(ogGetPath $EFIDIR/EFI/Microsoft/Boot/bootmgfw.efi)
138            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)" || return $?
139
140            # Crear orden de arranque (con unos valores por defecto).
141            ogNvramAddEntry $BOOTLABEL "/EFI${LOADER#*EFI}"
142            # Marcar próximo arranque y reiniciar.
143            ogNvramSetNext "$BOOTLABEL"
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#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
778#@author  Irina Gomez, ETSII Universidad de Sevilla
779#@date    2019-03-05
780#*/ ##
781
782function ogGrubInstallMbr ()
783{
784
785# Variables locales.
786local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
787local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB EFIBOOTDIR
788
789# Si se solicita, mostrar ayuda.
790if [ "$*" == "help" ]; then
791    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
792           "$FUNCNAME 1 1 FALSE " \
793           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
794    return
795fi 
796
797# Error si no se reciben 2 parámetros.
798[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
799
800
801DISK=$1; PART=$2;
802CHECKOS=${3:-"FALSE"}
803KERNELPARAM=$4
804BACKUPNAME=".backup.og"
805
806#Error si no es linux.
807#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
808#VERSION=$(ogGetOsVersion $DISK $PART)
809#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
810
811#La primera etapa del grub se fija en el primer disco duro
812FIRSTSTAGE=$(ogDiskToDev 1)
813
814#localizar disco segunda etapa del grub
815SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
816
817# prepara el directorio principal de la segunda etapa
818[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
819
820#Localizar directorio segunda etapa del grub   
821PREFIXSECONDSTAGE="/boot/grubMBR"
822
823# Instalamos grub para EFI en ESP
824EFIOPTGRUB=""
825# Desde el bootdir uefi y bios buscan el grub.cfg en subdirectorios distintos.
826EFIBOOTDIR=""
827if ogIsEfiActive; then
828    read EFIDISK EFIPART <<< $(ogGetEsp)
829    # Comprobamos que exista ESP y el directorio para ubuntu
830    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
831    if [ $? -ne 0 ]; then
832        ogFormat $EFIDISK $EFIPART FAT32
833        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
834    fi
835    EFISUBDIR="grub"
836    # Borramos la configuración anterior
837    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
838    mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
839    EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
840    EFIBOOTDIR="/boot"
841fi
842
843# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
844if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
845then
846        # Si no se reconfigura se utiliza el grub.cfg orginal
847        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
848        # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
849        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
850        # Reactivamos el grub con el grub.cfg original.
851        grub-install --force ${EFIOPTGRUB} --boot-directory=${SECONDSTAGE}${EFIBOOTDIR} $FIRSTSTAGE
852        EVAL=$?
853else
854        # SI Reconfigurar segunda etapa (grub.cfg) == TRUE
855
856        #llamada a updateBootCache para que aloje la primera fase del ogLive
857        updateBootCache
858
859        if ogIsEfiActive; then
860            # UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
861            if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
862                 [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
863            fi
864        else
865            #Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
866            mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
867        fi
868
869        #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
870        echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
871        echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
872
873
874        #Preparar configuración segunda etapa: crear ubicacion
875        mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
876        #Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
877        sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
878        /etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
879        #Preparar configuración segunda etapa: crear entrada del sistema operativo
880        grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
881
882
883        # Renombramos la configuración de grub antigua
884        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
885
886        #Instalar el grub
887        grub-install --force ${EFIOPTGRUB} --boot-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE}${EFIBOOTDIR} $FIRSTSTAGE
888        EVAL=$?
889fi
890
891# Movemos el grubx64.efi
892if ogIsEfiActive; then
893    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
894    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
895    cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
896    # Nombre OpenGnsys para cargador
897    cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{shimx64.efi,ogloader.efi}
898fi
899return $EVAL
900}
901
902
903#/**
904#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
905#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
906#@param   int_disk_SecondStage     
907#@param   int_part_SecondStage     
908#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
909#@param   str "kernel param "   
910#@return 
911#@exception OG_ERR_FORMAT    Formato incorrecto.
912#@version 1.0.2 - Primeras pruebas.
913#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
914#@date    2011-10-29
915#@version 1.0.3 - Soporte para linux de 32 y 64 bits
916#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
917#@date    2012-03-13
918#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
919#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
920#@date    2012-03-13
921#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
922#@author Irina Gomez, ETSII Universidad de Sevilla
923#@date    2019-01-08
924#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
925#@author  Irina Gomez, ETSII Universidad de Sevilla
926#@date    2019-03-05
927#*/ ##
928
929function ogGrubInstallPartition ()
930{
931
932# Variables locales.
933local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
934local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB EFIBOOTDIR
935
936# Si se solicita, mostrar ayuda.
937if [ "$*" == "help" ]; then
938    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
939           "$FUNCNAME 1 1 FALSE " \
940           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
941    return
942fi 
943
944# Error si no se reciben 2 parámetros.
945[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
946
947DISK=$1; PART=$2;
948CHECKOS=${3:-"FALSE"}
949KERNELPARAM=$4
950BACKUPNAME=".backup.og"
951
952#error si no es linux.
953VERSION=$(ogGetOsVersion $DISK $PART)
954echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
955
956#Localizar primera etapa del grub
957FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
958
959#localizar disco segunda etapa del grub
960SECONDSTAGE=$(ogMount $DISK $PART)
961
962#Localizar directorio segunda etapa del grub   
963PREFIXSECONDSTAGE="/boot/grubPARTITION"
964
965# Si es EFI instalamos el grub en la ESP
966EFIOPTGRUB=""
967# Desde el bootdir uefi y bios buscan el grub.cfg en subdirectorios distintos.
968EFIBOOTDIR=""
969if ogIsEfiActive; then
970    read EFIDISK EFIPART <<< $(ogGetEsp)
971    # Comprobamos que exista ESP y el directorio para ubuntu
972    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
973    if [ $? -ne 0 ]; then
974        ogFormat $EFIDISK $EFIPART FAT32
975        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
976    fi
977    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
978    # Borramos la configuración anterior
979    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
980    mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
981    EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
982    EFIBOOTDIR="/boot"
983fi
984
985# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
986if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
987then
988        # Si no se reconfigura se utiliza el grub.cfg orginal
989        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
990                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
991        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
992        # Reactivamos el grub con el grub.cfg original.
993        grub-install --force ${EFIOPTGRUB} --boot-directory=${SECONDSTAGE}${EFIBOOTDIR} $FIRSTSTAGE
994        EVAL=$?
995else
996        # SI Reconfigurar segunda etapa (grub.cfg) == TRUE
997
998        if ogIsEfiActive; then
999            # UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
1000            if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
1001                 [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
1002            fi
1003        else
1004            #Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
1005            mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
1006        fi
1007
1008        #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1009        echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1010        echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1011
1012        #Preparar configuración segunda etapa: crear ubicacion
1013        mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
1014        #Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
1015        sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
1016        # Para ogLive 5.0 (no afecta a os demás)
1017        sed -i /quick_boot/i"pkgdatadir=\$\{datarootdir\}\/grub" /etc/grub.d/00_header
1018        /etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
1019        #Preparar configuración segunda etapa: crear entrada del sistema operativo
1020        grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
1021
1022        # Renombramos la configuración de grub antigua
1023        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
1024
1025        #Instalar el grub
1026        grub-install --force ${EFIOPTGRUB} --boot-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE}${EFIBOOTDIR} $FIRSTSTAGE
1027        EVAL=$?
1028fi
1029
1030# Movemos el grubx64.efi
1031if ogIsEfiActive; then
1032    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
1033    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
1034    cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi
1035    # Nombre OpenGnsys para cargador
1036    cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{shimx64.efi,ogloader.efi}
1037fi
1038
1039return $EVAL
1040}
1041
1042
1043#/**
1044#         ogConfigureFstab int_ndisk int_nfilesys
1045#@brief   Configura el fstab según particiones existentes
1046#@param   int_ndisk      nº de orden del disco
1047#@param   int_nfilesys   nº de orden del sistema de archivos
1048#@return  (nada)
1049#@exception OG_ERR_FORMAT    Formato incorrecto.
1050#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
1051#@warning Puede haber un error si hay más de 1 partición swap.
1052#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
1053#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1054#@date    2013-03-21
1055#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
1056#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1057#@date    2016-11-03
1058#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
1059#@author  Irina Gómez, ETSII Universidad de Sevilla
1060#@date    2018-12-13
1061#*/ ##
1062function ogConfigureFstab ()
1063{
1064# Variables locales.
1065local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
1066local EFIDISK EFIPART EFIDEV EFIOPT
1067
1068# Si se solicita, mostrar ayuda.
1069if [ "$*" == "help" ]; then
1070    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1071           "$FUNCNAME 1 1"
1072    return
1073fi
1074# Error si no se reciben 2 parámetros.
1075[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1076# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
1077FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
1078[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
1079
1080# Hacer copia de seguridad del fichero fstab original.
1081cp -a ${FSTAB} ${FSTAB}.backup
1082# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
1083DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
1084PARTROOT=$(ogDiskToDev $1 $2)
1085# Configuración de swap (solo 1ª partición detectada).
1086PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
1087if [ -n "$PARTSWAP" ]
1088then
1089    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
1090    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
1091    if [ -n "$DEFSWAP" ]
1092    then
1093        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
1094        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1095    else
1096        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
1097        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1098        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
1099    fi 
1100else
1101    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
1102    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
1103fi
1104# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
1105if ogIsEfiActive; then
1106    read EFIDISK EFIPART <<< $(ogGetEsp)
1107    EFIDEV=$(ogDiskToDev $EFIDISK $EFIPART)
1108
1109    # Opciones de la partición ESP: si no existe ponemos un valor por defecto
1110    EFIOPT=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
1111    [ "$EFIOPT" == "" ] && EFIOPT='vfat\tumask=0077\t0\t1'
1112
1113    sed -i /"boot\/efi"/d  ${FSTAB}
1114    echo -e "$EFIDEV\t/boot/efi\t$EFIOPT" >> ${FSTAB}
1115fi
1116}
1117
1118#/**
1119#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
1120#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
1121#@param   int_ndisk      nº de orden del disco
1122#@param   int_nfilesys   nº de orden del sistema de archivos
1123#@param   str_name       nombre asignado (opcional)
1124#@return  (nada)
1125#@exception OG_ERR_FORMAT    Formato incorrecto.
1126#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1127#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1128#@note    Si no se indica nombre, se asigna un valor por defecto.
1129#@version 1.0.5 - Primera versión para OpenGnSys.
1130#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1131#@date    2013-03-21
1132#*/ ##
1133function ogSetLinuxName ()
1134{
1135# Variables locales.
1136local MNTDIR ETC NAME
1137
1138# Si se solicita, mostrar ayuda.
1139if [ "$*" == "help" ]; then
1140    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
1141           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
1142    return
1143fi
1144# Error si no se reciben 2 o 3 parámetros.
1145case $# in
1146    2)   # Asignar nombre automático (por defecto, "pc").
1147         NAME="$(ogGetHostname)"
1148         NAME=${NAME:-"pc"} ;;
1149    3)   # Asignar nombre del 3er parámetro.
1150         NAME="$3" ;;
1151    *)   # Formato de ejecución incorrecto.
1152         ogRaiseError $OG_ERR_FORMAT
1153         return $?
1154esac
1155
1156# Montar el sistema de archivos.
1157MNTDIR=$(ogMount $1 $2) || return $?
1158
1159ETC=$(ogGetPath $1 $2 /etc)
1160
1161if [ -d "$ETC" ]; then
1162        #cambio de nombre en hostname
1163        echo "$NAME" > $ETC/hostname
1164        #Opcion A para cambio de nombre en hosts
1165        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
1166        #Opcion B componer fichero de hosts
1167        cat > $ETC/hosts <<EOF
1168127.0.0.1       localhost
1169127.0.1.1       $NAME
1170
1171# The following lines are desirable for IPv6 capable hosts
1172::1     ip6-localhost ip6-loopback
1173fe00::0 ip6-localnet
1174ff00::0 ip6-mcastprefix
1175ff02::1 ip6-allnodes
1176ff02::2 ip6-allrouters
1177EOF
1178fi
1179}
1180
1181
1182
1183#/**
1184#         ogCleanLinuxDevices int_ndisk int_nfilesys
1185#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
1186#@param   int_ndisk      nº de orden del disco
1187#@param   int_nfilesys   nº de orden del sistema de archivos
1188#@return  (nada)
1189#@exception OG_ERR_FORMAT    Formato incorrecto.
1190#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1191#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1192#@version 1.0.5 - Primera versión para OpenGnSys.
1193#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1194#@date    2013-03-21
1195#@version 1.0.6b - Elimina fichero resume de hibernacion
1196#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1197#@date    2016-11-07
1198#*/ ##
1199function ogCleanLinuxDevices ()
1200{
1201# Variables locales.
1202local MNTDIR
1203
1204# Si se solicita, mostrar ayuda.
1205if [ "$*" == "help" ]; then
1206    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1207           "$FUNCNAME 1 1"
1208    return
1209fi
1210# Error si no se reciben 2 parámetros.
1211[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1212
1213# Montar el sistema de archivos.
1214MNTDIR=$(ogMount $1 $2) || return $?
1215
1216# Eliminar fichero de configuración de udev para dispositivos fijos de red.
1217[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
1218# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
1219[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
1220}
1221
1222#/**
1223# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
1224#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1225#@param 1 Numero de disco
1226#@param 2 Numero de particion
1227#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1228#@param 4 offline  configura el modo offline [offline|online] (opcional)
1229#@return  (nada)
1230#@exception OG_ERR_FORMAT    Formato incorrecto.
1231#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1232#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1233# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
1234#@version 1.0.6 - Prmera integración
1235#@author 
1236#@date    2016-11-07
1237#@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.
1238#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1239#@date    2017-06-17
1240#*/ ##
1241
1242
1243function ogGrubAddOgLive ()
1244{
1245    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
1246
1247    # Si se solicita, mostrar ayuda.
1248    if [ "$*" == "help" ]; then
1249        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1250                "$FUNCNAME 1 1" \
1251                "$FUNCNAME 1 6 15 offline"
1252        return
1253    fi
1254
1255    # Error si no se reciben 2 parámetros.
1256    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
1257    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
1258
1259    # Error si no existe el kernel y el initrd en la cache.
1260    # Falta crear nuevo codigo de error.
1261    [ -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 $?)
1262
1263    # Archivo de configuracion del grub
1264    DIRMOUNT=$(ogMount $1 $2)
1265    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1266
1267    # Error si no existe archivo del grub
1268    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1269
1270    # Si existe la entrada de opengnsys, se borra
1271    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
1272
1273    # Tipo de tabla de particiones
1274    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1275
1276    # Localizacion de la cache
1277    read NUMDISK NUMPART <<< $(ogFindCache)
1278    let NUMDISK=$NUMDISK-1
1279    # kernel y sus opciones. Pasamos a modo usuario
1280    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
1281
1282    # Configuracion offline si existe parametro
1283    echo "$@" |grep offline &>/dev/null && STATUS=offline
1284    echo "$@" |grep online  &>/dev/null && STATUS=online
1285    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1286
1287    # Numero de línea de la primera entrada del grub.
1288    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1289    # Texto de la entrada de opengnsys
1290MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
1291\tinsmod part_$PARTTABLETYPE \n \
1292\tinsmod ext2 \n \
1293\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1294\tlinux $KERNEL \n \
1295\tinitrd /boot/${oglivedir}/oginitrd.img \n \
1296}"
1297
1298
1299    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1300    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1301
1302    # Ponemos que la entrada por defecto sea la primera.
1303    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1304
1305    # Si me dan valor para timeout lo cambio en el grub.
1306    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1307}
1308
1309#/**
1310# ogGrubHidePartitions num_disk num_part
1311#@brief ver ogBootLoaderHidePartitions
1312#@see ogBootLoaderHidePartitions
1313#*/ ##
1314function ogGrubHidePartitions ()
1315{
1316    # Si se solicita, mostrar ayuda.
1317    if [ "$*" == "help" ]; then
1318        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1319               "$FUNCNAME 1 6"
1320        return
1321    fi
1322    ogBootLoaderHidePartitions $@
1323    return $?
1324}
1325
1326#/**
1327# ogBurgHidePartitions num_disk num_part
1328#@brief ver ogBootLoaderHidePartitions
1329#@see ogBootLoaderHidePartitions
1330#*/ ##
1331function ogBurgHidePartitions ()
1332{
1333    # Si se solicita, mostrar ayuda.
1334    if [ "$*" == "help" ]; then
1335        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1336               "$FUNCNAME 1 6"
1337        return
1338    fi
1339    ogBootLoaderHidePartitions $@
1340    return $?
1341}
1342
1343#/**
1344# ogBootLoaderHidePartitions num_disk num_part
1345#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
1346#@param 1 Numero de disco
1347#@param 2 Numero de particion
1348#@return  (nada)
1349#@exception OG_ERR_FORMAT    Formato incorrecto.
1350#@exception No existe archivo de configuracion del grub/burg.
1351#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1352#@author  Irina Gomez, ETSII Universidad de Sevilla
1353#@date    2015-11-17
1354#@version 1.1 Se generaliza la función para grub y burg
1355#@author  Irina Gomez, ETSII Universidad de Sevilla
1356#@date    2017-10-20
1357#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1358#@author  Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
1359#@date    2018-07-05
1360#*/
1361
1362function ogBootLoaderHidePartitions ()
1363{
1364    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1365
1366    # Si se solicita, mostrar ayuda.
1367    if [ "$*" == "help" ]; then
1368        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions or ogBurgHidePartitions."
1369        return
1370    fi
1371
1372    # Nombre de la función que llama a esta.
1373    FUNC="${FUNCNAME[@]:1}"
1374    FUNC="${FUNC%%\ *}"
1375
1376    # Error si no se reciben 2 parámetros.
1377    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1378
1379    # Archivo de configuracion del grub
1380    DIRMOUNT=$(ogMount $1 $2)
1381    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1382    case "$FUNC" in
1383        ogGrubHidePartitions)
1384            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1385            ;;
1386        ogBurgHidePartitions)
1387            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1388            ;;
1389        *)
1390            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1391            return $?
1392            ;;
1393    esac
1394
1395    # Error si no existe archivo del grub
1396    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
1397
1398    # Si solo hay una particion de Windows me salgo
1399    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
1400
1401    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
1402    sed -i '/parttool/d' $CFGFILE
1403
1404    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1405#   /*  (comentario de bloque para  Doxygen)
1406    # Entradas de Windows: numero de linea y particion. De mayor a menor.
1407    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
1408    #*/ (comentario para bloque Doxygen)
1409    # Particiones de Windows, pueden no estar en el grub.
1410    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
1411    # Modifico todas las entradas de Windows.
1412    for ENTRY in $WINENTRY; do
1413        LINE=${ENTRY%:*}
1414        PART=${ENTRY#*:}
1415        # En cada entrada, oculto o muestro cada particion.
1416        TEXT=""
1417        for PART2 in $WINPART; do
1418                # Muestro solo la particion de la entrada actual.
1419                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
1420
1421                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
1422        done
1423       
1424        sed -i "${LINE}a\ $TEXT" $CFGFILE
1425    done
1426
1427    # Activamos la particion que se inicia en todas las entradas de windows.
1428    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
1429
1430}
1431
1432#/**
1433# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
1434#@brief ver ogBootLoaderDeleteEntry
1435#@see ogBootLoaderDeleteEntry
1436#*/
1437function ogGrubDeleteEntry ()
1438{
1439    # Si se solicita, mostrar ayuda.
1440    if [ "$*" == "help" ]; then
1441        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1442                "$FUNCNAME 1 6 2 1"
1443        return
1444    fi
1445    ogBootLoaderDeleteEntry $@
1446    return $?
1447}
1448
1449#/**
1450# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
1451#@brief ver ogBootLoaderDeleteEntry
1452#@see ogBootLoaderDeleteEntry
1453#*/
1454function ogBurgDeleteEntry ()
1455{
1456    # Si se solicita, mostrar ayuda.
1457    if [ "$*" == "help" ]; then
1458        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1459                "$FUNCNAME 1 6 2 1"
1460        return
1461    fi
1462    ogBootLoaderDeleteEntry $@
1463    return $?
1464}
1465
1466#/**
1467# ogRefindDeleteEntry num_disk_delete num_part_delete
1468#@brief ver ogBootLoaderDeleteEntry
1469#@see ogBootLoaderDeleteEntry
1470#*/
1471function ogRefindDeleteEntry ()
1472{
1473    local EFIDISK EFIPART
1474    # Si se solicita, mostrar ayuda.
1475    if [ "$*" == "help" ]; then
1476        ogHelp  "$FUNCNAME" "$FUNCNAME int_disk_delete int_npartition_delete" \
1477                "$FUNCNAME 2 1"
1478        return
1479    fi
1480    read EFIDISK EFIPART <<< $(ogGetEsp)
1481    ogBootLoaderDeleteEntry $EFIDISK $EFIPART $@
1482    return $?
1483}
1484
1485#/**
1486# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1487#@brief Borra en el grub las entradas para el inicio en una particion.
1488#@param 1 Numero de disco donde esta el grub
1489#@param 2 Numero de particion donde esta el grub
1490#@param 3 Numero del disco del que borramos las entradas
1491#@param 4 Numero de la particion de la que borramos las entradas
1492#@note Tiene que ser llamada desde ogGrubDeleteEntry, ogBurgDeleteEntry o ogRefindDeleteEntry
1493#@return  (nada)
1494#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1495#@exception OG_ERR_FORMAT    Formato incorrecto.
1496#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1497#@version 1.1 Se generaliza la función para grub y burg
1498#@author  Irina Gomez, ETSII Universidad de Sevilla
1499#@date    2017-10-20
1500#*/ ##
1501
1502function ogBootLoaderDeleteEntry ()
1503{
1504    local FUNC DIRMOUNT CFGFILE LABEL MENUENTRY DELETEENTRY ENDENTRY ENTRY
1505
1506    # Si se solicita, mostrar ayuda.
1507    if [ "$*" == "help" ]; then
1508        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry, ogGrubDeleteEntry or ogRefindDeleteEntry"
1509        return
1510    fi
1511
1512    # Si el número de parámetros menos que 4 nos salimos
1513    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1514 
1515
1516    # Nombre de la función que llama a esta.
1517    FUNC="${FUNCNAME[@]:1}"
1518    FUNC="${FUNC%%\ *}"
1519
1520    # Archivo de configuracion del grub
1521    DIRMOUNT=$(ogMount $1 $2)
1522    # La función debe ser llamanda desde ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry.
1523    case "$FUNC" in
1524        ogGrubDeleteEntry)
1525            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1526            ;;
1527        ogBurgDeleteEntry)
1528            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1529            ;;
1530        ogRefindDeleteEntry)
1531            CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
1532            ;;
1533        *)
1534            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry."
1535            return $?
1536            ;;
1537    esac
1538
1539    # Dispositivo
1540    if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1541        LABEL=$(printf "Part-%02d-%02d" $3 $4)
1542    else
1543        LABEL=$(ogDiskToDev $3 $4)
1544    fi
1545
1546    # Error si no existe archivo de configuración
1547    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
1548
1549    # Numero de linea de cada entrada.
1550    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1551
1552    # Entradas que hay que borrar.
1553    DELETEENTRY=$(grep -n menuentry.*$LABEL $CFGFILE| cut -d: -f1)
1554
1555    # Si no hay entradas para borrar me salgo con aviso
1556    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $LABEL" || return $?
1557
1558    # Recorremos el fichero del final hacia el principio.
1559    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1560    for ENTRY in $MENUENTRY; do
1561        # Comprobamos si hay que borrar la entrada.
1562        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1563            let ENDENTRY=$ENDENTRY-1
1564            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1565        fi
1566
1567        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1568        ENDENTRY=$ENTRY
1569    done
1570}
1571
1572#/**
1573#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1574#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1575#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1576#@param   int_disk_SecondStage     
1577#@param   int_part_SecondStage     
1578#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1579#@return 
1580#@exception OG_ERR_FORMAT    Formato incorrecto.
1581#@exception OG_ERR_PARTITION  Partición no soportada
1582#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1583#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1584#@date    2017-06-23
1585#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1586#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1587#@date    2018-01-21
1588#@version 1.1.0 - Refactorizar fichero de configuacion
1589#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1590#@date    2018-01-24
1591#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1592#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1593#@date    2018-07-05
1594#*/ ##
1595
1596function ogBurgInstallMbr ()
1597{
1598 
1599# Variables locales.
1600local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1601
1602# Si se solicita, mostrar ayuda.
1603if [ "$*" == "help" ]; then
1604    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1605           "$FUNCNAME 1 1 FALSE " \
1606           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1607    return
1608fi 
1609
1610# Error si no se reciben 2 parametros.
1611[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1612
1613
1614DISK=$1; PART=$2;
1615CHECKOS=${3:-"FALSE"}
1616KERNELPARAM=$4
1617BACKUPNAME=".backup.og"
1618
1619#Error si no es linux.
1620ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1621
1622
1623#La primera etapa del grub se fija en el primer disco duro
1624FIRSTSTAGE=$(ogDiskToDev 1)
1625
1626#localizar disco segunda etapa del grub
1627SECONDSTAGE=$(ogMount $DISK $PART)
1628
1629# prepara el directorio principal de la segunda etapa (y copia los binarios)
1630[ -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)
1631
1632#Copiamos el tema
1633mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1634cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
1635
1636#Localizar directorio segunda etapa del grub   
1637#PREFIXSECONDSTAGE="/boot/burg/"
1638
1639# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1640if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1641then
1642    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1643    then
1644        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1645        return $?
1646    fi
1647fi
1648
1649# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1650
1651#llamada a updateBootCache para que aloje la primera fase del ogLive
1652updateBootCache
1653
1654#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1655echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1656echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1657
1658
1659#Preparar configuración segunda etapa: crear ubicacion
1660mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1661
1662#Preparar configuración segunda etapa: crear cabecera del fichero
1663#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1664
1665FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1666
1667#/* ## (comentario Dogygen)
1668cat > "$FILECFG" << EOF
1669
1670set theme_name=OpenGnsys
1671set gfxmode=1024x768
1672
1673
1674set locale_dir=(\$root)/boot/burg/locale
1675
1676set default=0
1677set timeout=25
1678set lang=es
1679
1680
1681insmod ext2
1682insmod gettext
1683
1684
1685
1686
1687if [ -s \$prefix/burgenv ]; then
1688  load_env
1689fi
1690
1691
1692
1693if [ \${prev_saved_entry} ]; then
1694  set saved_entry=\${prev_saved_entry}
1695  save_env saved_entry
1696  set prev_saved_entry=
1697  save_env prev_saved_entry
1698  set boot_once=true
1699fi
1700
1701function savedefault {
1702  if [ -z \${boot_once} ]; then
1703    saved_entry=\${chosen}
1704    save_env saved_entry
1705  fi
1706}
1707function select_menu {
1708  if menu_popup -t template_popup theme_menu ; then
1709    free_config template_popup template_subitem menu class screen
1710    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1711    save_env theme_name
1712    menu_refresh
1713  fi
1714}
1715
1716function toggle_fold {
1717  if test -z $theme_fold ; then
1718    set theme_fold=1
1719  else
1720    set theme_fold=
1721  fi
1722  save_env theme_fold
1723  menu_refresh
1724}
1725function select_resolution {
1726  if menu_popup -t template_popup resolution_menu ; then
1727    menu_reload_mode
1728    save_env gfxmode
1729  fi
1730}
1731
1732
1733if test -f \${prefix}/themes/\${theme_name}/theme ; then
1734  insmod coreui
1735  menu_region.text
1736  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1737  load_config \${prefix}/themes/conf.d/10_hotkey   
1738  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1739  insmod vbe
1740  insmod png
1741  insmod jpeg
1742  set gfxfont="Unifont Regular 16"
1743  menu_region.gfx
1744  vmenu resolution_menu
1745  controller.ext
1746fi
1747
1748
1749EOF
1750#*/ ## (comentario Dogygen)
1751
1752#Preparar configuración segunda etapa: crear entrada del sistema operativo
1753grubSyntax "$KERNELPARAM" >> "$FILECFG"
1754
1755#Instalar el burg
1756burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1757}
1758
1759#/**
1760# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1761#@brief ver ogBootLoaderDefaultEntry
1762#@see ogBootLoaderDefaultEntry
1763#*/ ##
1764function ogGrubDefaultEntry ()
1765{
1766    # Si se solicita, mostrar ayuda.
1767    if [ "$*" == "help" ]; then
1768        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1769               "$FUNCNAME 1 6 1 1"
1770        return
1771    fi
1772    ogBootLoaderDefaultEntry $@
1773    return $?
1774}
1775
1776#/**
1777# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1778#@brief ver ogBootLoaderDefaultEntry
1779#@see ogBootLoaderDefaultEntry
1780#*/ ##
1781function ogBurgDefaultEntry ()
1782{
1783    # Si se solicita, mostrar ayuda.
1784    if [ "$*" == "help" ]; then
1785        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1786               "$FUNCNAME 1 6 1 1"
1787        return
1788    fi
1789    ogBootLoaderDefaultEntry $@
1790    return $?
1791}
1792
1793
1794#/**
1795# ogRefindDefaultEntry int_disk_default_entry int_npartition_default_entry
1796#@brief ver ogBootLoaderDefaultEntry
1797#@see ogBootLoaderDefaultEntry
1798#*/ ##
1799function ogRefindDefaultEntry ()
1800{
1801    local EFIDISK EFIPART
1802    # Si se solicita, mostrar ayuda.
1803    if [ "$*" == "help" ]; then
1804        ogHelp "$FUNCNAME" "$FUNCNAME int_disk_default_entry int_npartition_default_entry" \
1805               "$FUNCNAME 1 1"
1806        return
1807    fi
1808
1809    read EFIDISK EFIPART <<< $(ogGetEsp)
1810    ogBootLoaderDefaultEntry $EFIDISK $EFIPART $@
1811    return $?
1812}
1813
1814#/**
1815# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1816#@brief   Configura la entrada por defecto de Burg
1817#@param   int_disk_SecondStage     
1818#@param   int_part_SecondStage     
1819#@param   int_disk_default_entry
1820#@param   int_part_default_entry
1821#@return 
1822#@exception OG_ERR_FORMAT    Formato incorrecto.
1823#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1824#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1825#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1826#@version 1.1.0 - Define la entrada por defecto del Burg
1827#@author  Irina Gomez, ETSII Universidad de Sevilla
1828#@date    2017-08-09
1829#@version 1.1 Se generaliza la función para grub y burg
1830#@author  Irina Gomez, ETSII Universidad de Sevilla
1831#@date    2018-01-04
1832#*/ ##
1833function ogBootLoaderDefaultEntry ()
1834{
1835
1836# Variables locales.
1837local PART FUNC DIRMOUNT LABEL CFGFILE DEFAULTENTRY MENUENTRY MSG
1838
1839# Si se solicita, mostrar ayuda.
1840if [ "$*" == "help" ]; then
1841    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
1842    return
1843fi 
1844
1845# Nombre de la función que llama a esta.
1846FUNC="${FUNCNAME[@]:1}"
1847FUNC="${FUNC%%\ *}"
1848
1849# Error si no se reciben 3 parametros.
1850[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1851
1852# Error si no puede montar sistema de archivos.
1853DIRMOUNT=$(ogMount $1 $2) || return $?
1854
1855# Comprobamos que exista fichero de configuración
1856# La función debe ser llamanda desde ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry.
1857case "$FUNC" in
1858    ogGrubDefaultEntry)
1859        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1860        ;;
1861    ogBurgDefaultEntry)
1862        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1863        ;;
1864    ogRefindDefaultEntry)
1865        CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
1866        ;;
1867    *)
1868        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
1869        return $?
1870        ;;
1871esac
1872
1873# Error si no existe archivo de configuración
1874[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1875
1876# Dispositivo
1877if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1878    LABEL=$(printf "Part-%02d-%02d" $3 $4)
1879else
1880    LABEL=$(ogDiskToDev $3 $4)
1881fi
1882
1883# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1884DEFAULTENTRY=$(grep -n -m 1 menuentry.*$LABEL $CFGFILE| cut -d: -f1)
1885
1886# Si no hay entradas para borrar me salgo con aviso
1887[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $LABEL" || return $?
1888
1889# Número de la de linea por defecto en el menú de usuario
1890MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1891
1892if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1893    sed -i /default_selection.*$/d $CFGFILE
1894    sed -i "1 i\default_selection $MENUENTRY" $CFGFILE
1895else
1896    # En grub y burg las líneas empiezan a contar desde cero
1897    let MENUENTRY=$MENUENTRY-1
1898    sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1899fi
1900MSG="MSG_HELP_$FUNC"
1901echo "${!MSG%%\.}: $@"
1902}
1903
1904#/**
1905# ogGrubOgliveDefaultEntry num_disk num_part
1906#@brief ver ogBootLoaderOgliveDefaultEntry
1907#@see ogBootLoaderOgliveDefaultEntry
1908#*/ ##
1909function ogGrubOgliveDefaultEntry ()
1910{
1911    # Si se solicita, mostrar ayuda.
1912    if [ "$*" == "help" ]; then
1913        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1914               "$FUNCNAME 1 6"
1915        return
1916    fi
1917    ogBootLoaderOgliveDefaultEntry $@
1918    return $?
1919}
1920
1921#/**
1922# ogBurgOgliveDefaultEntry num_disk num_part
1923#@brief ver ogBootLoaderOgliveDefaultEntry
1924#@see ogBootLoaderOgliveDefaultEntry
1925#*/ ##
1926function ogBurgOgliveDefaultEntry ()
1927{
1928    # Si se solicita, mostrar ayuda.
1929    if [ "$*" == "help" ]; then
1930        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1931               "$FUNCNAME 1 6"
1932        return
1933    fi
1934    ogBootLoaderOgliveDefaultEntry $@
1935    return $?
1936}
1937
1938
1939#/**
1940# ogRefindOgliveDefaultEntry
1941#@brief ver ogBootLoaderOgliveDefaultEntry
1942#@see ogBootLoaderOgliveDefaultEntry
1943#*/ ##
1944function ogRefindOgliveDefaultEntry ()
1945{
1946    local EFIDISK EFIPART
1947    # Si se solicita, mostrar ayuda.
1948    if [ "$*" == "help" ]; then
1949        ogHelp "$FUNCNAME" "$FUNCNAME" \
1950               "$FUNCNAME"
1951        return
1952    fi
1953
1954    read EFIDISK EFIPART <<< $(ogGetEsp)
1955    ogBootLoaderOgliveDefaultEntry $EFIDISK $EFIPART
1956    return $?
1957}
1958
1959
1960#/**
1961# ogBootLoaderOgliveDefaultEntry
1962#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1963#@param   int_disk_SecondStage     
1964#@param   int_part_SecondStage     
1965#@return 
1966#@exception OG_ERR_FORMAT    Formato incorrecto.
1967#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1968#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1969#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1970#@version 1.1.0 - Primeras pruebas con Burg
1971#@author  Irina Gomez, ETSII Universidad de Sevilla
1972#@date    2017-08-09
1973#@version 1.1 Se generaliza la función para grub y burg
1974#@author  Irina Gomez, ETSII Universidad de Sevilla
1975#@date    2018-01-04
1976#*/ ##
1977function  ogBootLoaderOgliveDefaultEntry ()
1978{
1979
1980# Variables locales.
1981local FUNC PART CFGFILE NUMENTRY MSG
1982
1983# Si se solicita, mostrar ayuda.
1984if [ "$*" == "help" ]; then
1985    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry" \
1986    return
1987fi 
1988
1989# Nombre de la función que llama a esta.
1990FUNC="${FUNCNAME[@]:1}"
1991FUNC="${FUNC%%\ *}"
1992
1993# Error si no se reciben 2 parametros.
1994[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1995
1996# Error si no puede montar sistema de archivos.
1997PART=$(ogMount $1 $2) || return $?
1998# La función debe ser llamanda desde ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry.
1999case "$FUNC" in
2000    ogGrubOgliveDefaultEntry)
2001        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
2002        ;;
2003    ogBurgOgliveDefaultEntry)
2004        CFGFILE="$PART/boot/burg/burg.cfg"
2005        ;;
2006    ogRefindOgliveDefaultEntry)
2007        CFGFILE="$PART/EFI/refind/refind.conf"
2008        ;;
2009    *)
2010        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry."
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 la entrada de ogLive
2019NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
2020
2021# Si no existe entrada de ogLive nos salimos
2022[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
2023
2024if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
2025    sed -i /default_selection.*$/d $CFGFILE
2026
2027    sed -i "1 i\default_selection $NUMENTRY" $CFGFILE
2028else
2029    let NUMENTRY=$NUMENTRY-1
2030    sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
2031fi
2032
2033MSG="MSG_HELP_$FUNC"
2034echo "${!MSG%%\.}: $@"
2035}
2036
2037
2038#/**
2039# ogGrubSetTheme num_disk num_part str_theme
2040#@brief ver ogBootLoaderSetTheme
2041#@see ogBootLoaderSetTheme
2042#*/ ##
2043function ogGrubSetTheme ()
2044{
2045    # Si se solicita, mostrar ayuda.
2046    if [ "$*" == "help" ]; then
2047        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
2048               "$FUNCNAME 1 4 ThemeBasic"\
2049               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2050        return
2051    fi
2052    ogBootLoaderSetTheme $@
2053    return $?
2054}
2055
2056#/**
2057# ogBurgSetTheme num_disk num_part str_theme
2058#@brief ver ogBootLoaderSetTheme
2059#@see ogBootLoaderSetTheme
2060#*/ ##
2061function ogBurgSetTheme  ()
2062{
2063    # Si se solicita, mostrar ayuda.
2064    if [ "$*" == "help" ]; then
2065        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
2066               "$FUNCNAME 1 4 ThemeBasic" \
2067               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2068        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
2069               
2070        return
2071    fi
2072    ogBootLoaderSetTheme $@
2073    return $?
2074}
2075
2076
2077#/**
2078# ogRefindSetTheme str_theme
2079#@brief ver ogBootLoaderSetTheme
2080#@see ogBootLoaderSetTheme
2081#*/ ##
2082function ogRefindSetTheme () {
2083    local PART DIRTHEME CFGFILE
2084    # Si se solicita, mostrar ayuda.
2085    if [ "$*" == "help" ]; then
2086        ogHelp "$FUNCNAME" "$FUNCNAME str_themeName" \
2087               "$FUNCNAME ThemeBasic"
2088        echo -e "\nThemes in $OGLIB/refind:\n$(ls $OGLIB/refind/themes/ 2>/dev/null)"
2089
2090        return
2091    fi
2092
2093    # Detectamos partición ESP
2094    read EFIDISK EFIPART <<< $(ogGetEsp)
2095
2096    PART=$(ogMount $EFIDISK $EFIPART) || return $?
2097    DIRTHEME="$PART/EFI/refind/themes"
2098    CFGFILE="$PART/EFI/refind/refind.conf"
2099
2100    # Para utilizar ogBootLoaderSetTheme es necesario la entrada set theme_name
2101    if [ -f $CFGFILE ]; then
2102        sed -i '1 i\set theme_name=none' $CFGFILE
2103    else
2104        ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2105    fi
2106    # Creamos el directorio para los temas
2107    [ -d $DIRTHEME ] || mkdir $DIRTHEME
2108
2109    ogBootLoaderSetTheme $EFIDISK $EFIPART $@
2110    return $?
2111}
2112
2113
2114#/**
2115# ogBootLoaderSetTheme
2116#@brief   asigna un tema al BURG
2117#@param   int_disk_SecondStage     
2118#@param   int_part_SecondStage 
2119#@param   str_theme_name   
2120#@return 
2121#@exception OG_ERR_FORMAT    Formato incorrecto.
2122#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2123#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg refind.conf.
2124#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2125#@exception OG_ERR_NOTFOUND  Fichero de configuración del tema no encontrado: theme.conf (sólo refind).
2126#@note    El tema debe situarse en OGLIB/BOOTLOADER/themes
2127#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2128#@author  Antonio J. Doblas Viso. Universidad de Malaga
2129#@date    2018-01-24
2130#@version 1.1.1 - Soporta rEFInd (ticket #802 #888).
2131#@author  Irina Gomez. Universidad de Sevilla
2132#@date    2019-03-22
2133#*/ ##
2134function  ogBootLoaderSetTheme ()
2135{
2136
2137# Variables locales.
2138local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG NEWTHEMECFG
2139
2140# Si se solicita, mostrar ayuda.
2141if [ "$*" == "help" ]; then
2142    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
2143    return   
2144fi
2145 
2146
2147NEWTHEME="$3"
2148
2149# Nombre de la función que llama a esta.
2150FUNC="${FUNCNAME[@]:1}"
2151FUNC="${FUNC%%\ *}"
2152
2153
2154
2155# Error si no se reciben 3 parametros.
2156[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
2157
2158# Error si no puede montar sistema de archivos.
2159PART=$(ogMount $1 $2) || return $?
2160# La función debe ser llamanda desde ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme.
2161case "$FUNC" in
2162    ogGrubSetTheme)
2163        BOOTLOADER="grub"
2164        BOOTLOADERDIR="boot/grubMBR"
2165        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2166        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
2167        return $?               
2168        ;;
2169    ogBurgSetTheme)
2170        BOOTLOADER="burg"
2171        BOOTLOADERDIR="boot/burg"
2172        CFGFILE="$PART/boot/burg/burg.cfg"       
2173        ;;
2174    ogRefindSetTheme)
2175        BOOTLOADER="refind"
2176        BOOTLOADERDIR="EFI/refind"
2177        CFGFILE="$PART/EFI/refind/refind.conf"
2178        ;;
2179    *)
2180        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
2181        return $?
2182        ;;
2183esac
2184
2185# Comprobamos que exista fichero de configuración
2186[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2187
2188# Detectamos cual es el tema asignado
2189THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
2190# Si no existe entrada de theme_name  nos salimos
2191[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
2192
2193#Actualizamos el tema del servidor a la particion
2194if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
2195        # Para refind es necesario que exista theme.conf en el directorio del tema.
2196        if [ "$BOOTLOADER" == "refind" ]; then
2197            NEWTHEMECFG="$OGLIB/$BOOTLOADER/themes/$NEWTHEME/theme.conf"
2198            [ -f $NEWTHEMECFG ] || ogRaiserError $OG_ERR_NOTFOUND "theme.conf" || return $?
2199            grep -v "^#" $NEWTHEMECFG >> $CFGFILE
2200            # eliminamos "set theme" es de grub y no de refind
2201            sed -i '/theme_name/d' $CFGFILE
2202        fi
2203        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/$BOOTLOADERDIR/themes/
2204fi
2205
2206#Verificamos que el tema esta en la particion
2207if ! [ -d $PART/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
2208                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/$BOOTLOADERDIR/themes/" || return $?
2209fi
2210
2211#Cambiamos la entrada el fichero de configuración.
2212sed --regexp-extended -i  s/"set theme_name=$THEME"/"set theme_name=$NEWTHEME"/g $CFGFILE
2213
2214
2215}
2216
2217#/**
2218# ogGrubSetAdminKeys num_disk num_part str_theme
2219#@brief ver ogBootLoaderSetTheme
2220#@see ogBootLoaderSetTheme
2221#*/ ##
2222function ogGrubSetAdminKeys ()
2223{
2224    # Si se solicita, mostrar ayuda.
2225    if [ "$*" == "help" ]; then
2226        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2227               "$FUNCNAME 1 4 FALSE "\
2228               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2229        return
2230    fi
2231    ogBootLoaderSetAdminKeys $@
2232    return $?
2233}
2234
2235#/**
2236# ogBurgSetAdminKeys num_disk num_part str_bolean
2237#@brief ver ogBootLoaderSetAdminKeys
2238#@see ogBootLoaderSetAdminKeys
2239#*/ ##
2240function ogBurgSetAdminKeys  ()
2241{
2242    # Si se solicita, mostrar ayuda.
2243    if [ "$*" == "help" ]; then
2244        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2245               "$FUNCNAME 1 4 TRUE" \
2246               "$FUNCNAME \$(ogFindCache) FALSE"               
2247        return
2248    fi
2249    ogBootLoaderSetAdminKeys $@
2250    return $?
2251}
2252
2253
2254
2255#/**
2256# ogBootLoaderSetAdminKeys
2257#@brief   Activa/Desactica las teclas de administracion
2258#@param   int_disk_SecondStage     
2259#@param   int_part_SecondStage 
2260#@param   Boolean TRUE/FALSE   
2261#@return 
2262#@exception OG_ERR_FORMAT    Formato incorrecto.
2263#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2264#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2265#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2266#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2267#@author  Antonio J. Doblas Viso. Universidad de Malaga
2268#@date    2018-01-24
2269#*/ ##
2270function  ogBootLoaderSetAdminKeys ()
2271{
2272
2273# Variables locales.
2274local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2275
2276# Si se solicita, mostrar ayuda.
2277if [ "$*" == "help" ]; then
2278    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2279    return   
2280fi
2281 
2282
2283# Nombre de la función que llama a esta.
2284FUNC="${FUNCNAME[@]:1}"
2285FUNC="${FUNC%%\ *}"
2286
2287
2288# Error si no se reciben 2 parametros.
2289[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2290
2291# Error si no puede montar sistema de archivos.
2292PART=$(ogMount $1 $2) || return $?
2293# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2294case "$FUNC" in
2295    ogGrubSetAdminKeys)
2296        BOOTLOADER="grub"
2297        BOOTLOADERDIR="grubMBR"
2298        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2299        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2300        return $?       
2301        ;;
2302    ogBurgSetAdminKeys)
2303        BOOTLOADER="burg"
2304        BOOTLOADERDIR="burg"
2305        CFGFILE="$PART/boot/burg/burg.cfg"       
2306        ;;
2307    *)
2308        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2309        return $?
2310        ;;
2311esac
2312
2313
2314# Comprobamos que exista fichero de configuración
2315[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2316
2317
2318case "$3" in
2319        true|TRUE)
2320                [ -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
2321        ;;
2322        false|FALSE)
2323                [ -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
2324        ;;     
2325        *)
2326           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2327        return $?
2328    ;; 
2329esac
2330}
2331
2332
2333
2334#/**
2335# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
2336#@brief ver ogBootLoaderSetTimeOut
2337#@see ogBootLoaderSetTimeOut
2338#*/ ##
2339function ogGrubSetTimeOut ()
2340{
2341    # Si se solicita, mostrar ayuda.
2342    if [ "$*" == "help" ]; then
2343        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2344               "$FUNCNAME 1 4 50 "\
2345               "$FUNCNAME \$(ogFindCache) 50"
2346        return
2347    fi
2348    ogBootLoaderSetTimeOut $@
2349    return $?
2350}
2351
2352#/**
2353# ogBurgSetTimeOut num_disk num_part str_bolean
2354#@brief ver ogBootLoaderSetTimeOut
2355#@see ogBootLoaderSetTimeOut
2356#*/ ##
2357function ogBurgSetTimeOut ()
2358{
2359    # Si se solicita, mostrar ayuda.
2360    if [ "$*" == "help" ]; then
2361        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2362               "$FUNCNAME 1 4 50" \
2363               "$FUNCNAME \$(ogFindCache) 50"               
2364        return
2365    fi
2366    ogBootLoaderSetTimeOut $@
2367    return $?
2368}
2369
2370
2371#/**
2372# ogRefindSetTimeOut int_timeout_second
2373#@brief ver ogBootLoaderSetTimeOut
2374#@see ogBootLoaderSetTimeOut
2375#*/ ##
2376function ogRefindSetTimeOut ()
2377{
2378    local EFIDISK EFIPART
2379    # Si se solicita, mostrar ayuda.
2380    if [ "$*" == "help" ]; then
2381        ogHelp "$FUNCNAME" "$FUNCNAME int_timeout_seconds" \
2382               "$FUNCNAME 50"
2383        return
2384    fi
2385
2386    read EFIDISK EFIPART <<< $(ogGetEsp)
2387    ogBootLoaderSetTimeOut $EFIDISK $EFIPART $@
2388    return $?
2389}
2390
2391#/**
2392# ogBootLoaderSetTimeOut
2393#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2394#@param   int_disk_SecondStage     
2395#@param   int_part_SecondStage 
2396#@param   int_timeout_seconds   
2397#@return 
2398#@exception OG_ERR_FORMAT    Formato incorrecto.
2399#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2400#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2401#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2402#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2403#@author  Antonio J. Doblas Viso. Universidad de Malaga
2404#@date    2018-01-24
2405#*/ ##
2406function  ogBootLoaderSetTimeOut ()
2407{
2408
2409# Variables locales.
2410local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2411
2412# Si se solicita, mostrar ayuda.
2413if [ "$*" == "help" ]; then
2414    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut"
2415    return   
2416fi
2417 
2418ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2419
2420# Nombre de la función que llama a esta.
2421FUNC="${FUNCNAME[@]:1}"
2422FUNC="${FUNC%%\ *}"
2423
2424# Error si no se reciben 3 parametros.
2425[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2426
2427# Error si no puede montar sistema de archivos.
2428PART=$(ogMount $1 $2) || return $?
2429# La función debe ser llamanda desde ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut.
2430case "$FUNC" in
2431    ogGrubSetTimeOut)
2432        BOOTLOADER="grub"
2433        BOOTLOADERDIR="boot/grubMBR"
2434        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2435        ;;
2436    ogBurgSetTimeOut)
2437        BOOTLOADER="burg"
2438        BOOTLOADERDIR="boot/burg"
2439        CFGFILE="$PART/boot/burg/burg.cfg"       
2440        ;;
2441    ogRefindSetTimeOut)
2442        BOOTLOADER="refind"
2443        BOOTLOADERDIR="EFI/refind"
2444        CFGFILE="$PART/EFI/refind/refind.conf"
2445        ;;
2446    *)
2447        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut."
2448        return $?
2449        ;;
2450esac
2451
2452# Comprobamos que exista fichero de configuración
2453[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2454
2455# Asignamos el timeOut.
2456if [ "$BOOTLOADER" == "refind" ]; then
2457    sed -i s/timeout.*$/"timeout $TIMEOUT"/g $CFGFILE
2458else
2459    sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2460fi
2461}
2462
2463
2464#/**
2465# ogGrubSetResolution num_disk num_part int_resolution
2466#@brief ver ogBootLoaderSetResolution
2467#@see ogBootLoaderSetResolution
2468#*/ ##
2469function ogGrubSetResolution ()
2470{
2471    # Si se solicita, mostrar ayuda.
2472    if [ "$*" == "help" ]; then
2473        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2474             "$FUNCNAME 1 4 1024x768" \
2475             "$FUNCNAME \$(ogFindCache) 1024x768" \
2476             "$FUNCNAME 1 4" 
2477        return
2478    fi
2479    ogBootLoaderSetResolution $@
2480    return $?
2481}
2482
2483#/**
2484# ogBurgSetResolution num_disk num_part str_bolean
2485#@brief ver ogBootLoaderSetResolution
2486#@see ogBootLoaderSetResolution
2487#*/ ##
2488function ogBurgSetResolution ()
2489 {
2490    # Si se solicita, mostrar ayuda.
2491    if [ "$*" == "help" ]; then
2492        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2493               "$FUNCNAME 1 4 1024x768" \
2494               "$FUNCNAME \$(ogFindCache) 1024x768" \
2495               "$FUNCNAME 1 4"               
2496        return
2497    fi
2498    ogBootLoaderSetResolution $@
2499    return $?
2500}
2501
2502
2503
2504#/**
2505# ogBootLoaderSetResolution
2506#@brief   Define la resolucion que usuara el thema del gestor de arranque
2507#@param   int_disk_SecondStage     
2508#@param   int_part_SecondStage 
2509#@param   str_resolution (Opcional)   
2510#@return 
2511#@exception OG_ERR_FORMAT    Formato incorrecto.
2512#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2513#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2514#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2515#@author  Antonio J. Doblas Viso. Universidad de Malaga
2516#@date    2018-01-24
2517#*/ ##
2518function  ogBootLoaderSetResolution ()
2519{
2520
2521# Variables locales.
2522local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2523
2524# Si se solicita, mostrar ayuda.
2525if [ "$*" == "help" ]; then
2526    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution, ogBurgSetResolution or ogRefindSetResolution."
2527    return   
2528fi
2529
2530
2531# Nombre de la función que llama a esta.
2532FUNC="${FUNCNAME[@]:1}"
2533FUNC="${FUNC%%\ *}"
2534
2535
2536# Error si no se reciben 2 parametros.
2537[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2538
2539# Error si no puede montar sistema de archivos.
2540PART=$(ogMount $1 $2) || return $?
2541# La función debe ser llamanda desde ogGrugSetResolution, ogBurgSetResolution or ogRefindSetResolution.
2542case "$FUNC" in
2543    ogGrubSetResolution)
2544        BOOTLOADER="grub"
2545        BOOTLOADERDIR="grubMBR"
2546        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2547        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2548        return $?     
2549        ;;
2550    ogBurgSetResolution)
2551        BOOTLOADER="burg"
2552        BOOTLOADERDIR="burg"
2553        CFGFILE="$PART/boot/burg/burg.cfg"       
2554        ;;
2555    *)
2556        ogRaiseError $OG_ERR_FORMAT "Use GrugSetResolution, ogBurgSetResolution or ogRefindSetResolution."
2557        return $?
2558        ;;
2559esac
2560
2561DEFAULTRESOLUTION=1024x768
2562
2563# Comprobamos que exista fichero de configuración
2564[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2565
2566#controlar variable a consierar vga (default template) o video (menu)
2567#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2568if [ $# -eq 2 ] ; then 
2569        if [ -n $video ]; then
2570                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2571        fi
2572        if [ -n $vga ] ; then
2573        case "$vga" in
2574                788|789|814)
2575                        NEWRESOLUTION=800x600
2576                        ;;
2577                791|792|824)
2578                        NEWRESOLUTION=1024x768
2579                        ;;
2580                355)
2581                        NEWRESOLUTION=1152x864
2582                        ;;
2583                794|795|829)
2584                        NEWRESOLUTION=1280x1024
2585                        ;;
2586        esac
2587        fi
2588fi
2589
2590if [ $# -eq 3 ] ; then
2591        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2592        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"
2593fi
2594
2595# Si no existe NEWRESOLUCION  asignamos la defaulT
2596[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2597
2598#Cambiamos la entrada el fichero de configuración.
2599sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2600}
2601
2602
2603
2604
2605#/**
2606# ogBootLoaderSetResolution
2607#@brief   Define la resolucion que usuara el thema del gestor de arranque
2608#@param   int_resolution1
2609#@param   int_resolution2 (Opcional)
2610#@return
2611#@exception OG_ERR_FORMAT    Formato incorrecto.
2612#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2613#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2614#*/ ##
2615function ogRefindSetResolution () {
2616local PART CFGFILE
2617# Si se solicita, mostrar ayuda.
2618if [ "$*" == "help" ]; then
2619    ogHelp "$FUNCNAME" "$FUNCNAME int_resolution1 [int_resolution2]" \
2620       "$FUNCNAME 1366 768" \
2621       "$FUNCNAME 1"
2622    return
2623fi
2624
2625    # Error si no se reciben 2 parametros.
2626[ $# -ge 1 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_resolution1 [int_resolution2]" || return $?
2627
2628# Error si no puede montar sistema de archivos.
2629PART=$(ogMount $(ogGetEsp)) || return $?
2630
2631# Comprobamos que exista fichero de configuración
2632CFGFILE=$PART/EFI/refind/refind.conf
2633[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2634
2635# Borramos resolucion anterior y configuramos la nueva
2636sed -i /^resolution/d $CFGFILE
2637
2638sed -i "1 i\resolution $1 $2" $CFGFILE
2639}
2640
2641#         ogRefindInstall bool_autoconfig
2642#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2643#@param   bolean_Check__auto_config   true | false[default]
2644#@return
2645#@exception OG_ERR_FORMAT    Formato incorrecto.
2646#@exception OG_ERR_NOTFOUND  No se encuentra la partición ESP.
2647#@exception OG_ERR_NOTFOUND  No se encuentra shimx64.efi.signed.
2648#@exception OG_ERR_NOTFOUND  No se encuentra refind-install o refind en OGLIB
2649#@exception OG_ERR_PARTITION No se puede montar la partición ESP.
2650#@note    Refind debe estar instalado en el ogLive o compartido en OGLIB
2651#@version 1.1.0 - Primeras pruebas.
2652#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2653#@date    2017-06-26
2654#@version 1.1.1 - Usa refind-install. Obtiene partición con ogGetEsp. Configura Part-X-Y y ogLive.
2655#@author  Irina Gomez. Universidad de Sevilla.
2656#@date    2019-03-22
2657#*/ ##
2658function ogRefindInstall () {
2659# Variables locales.
2660local CONFIG EFIDISK EFIPART EFIDEVICE EFIMNT EFIDIR SHIM REFINDDIR
2661local CACHEDEVICE OGLIVE OGLIVEDIR CMDLINE OGICON CFGFILE DEVICES
2662local LNXCFGFILE NUMENTRY DIR
2663
2664# Si se solicita, mostrar ayuda.
2665if [ "$*" == "help" ]; then
2666    ogHelp "$FUNCNAME" "$FUNCNAME boolean_autoconfig " \
2667           "$FUNCNAME TRUE"
2668    return
2669fi
2670
2671# Recogemos parametros
2672CONFIG=${1:-"FALSE"}
2673
2674read -e EFIDISK EFIPART  <<< $(ogGetEsp)
2675EFIDEVICE=$(ogDiskToDev $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_NOTFOUND "ESP" || return $?
2676EFIMNT=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR mount ESP" || return $?
2677EFIDIR="$EFIMNT/EFI"
2678[ -d $EFIDIR ] || mkdir $EFIDIR
2679
2680# Instalamos rEFInd. Con refind-install o copiandolo del OGLIB
2681if which refind-install &>/dev/null; then
2682    # Comprobamos que exista shimx64
2683    SHIM=$(ogGetPath /usr/lib/shim/shimx64.efi.signed)
2684    [ "$SHIM" == "" ] && return $(ogRaiseError $OG_ERR_NOTFOUND "shimx64.efi.signed")
2685
2686    refind-install --yes --alldrivers --usedefault $EFIDEVICE  --shim $SHIM
2687
2688    # Cambiamos el nombre del directorio
2689    [ -d $EFIDIR/refind ] && rm -rf $EFIDIR/refind
2690    mv $EFIDIR/BOOT  $EFIDIR/refind
2691
2692    # Desmontamos directorio temporal (para idempotencia)
2693    umount /tmp/refind_install
2694else
2695    REFINDDIR=$OGLIB/refind
2696    [ -d $REFINDDIR ] || ogRaiseError $OG_ERR_NOTFOUND "refind-install or $REFINDDIR" || return $?
2697    cp -r $REFINDDIR $EFIDIR
2698fi
2699# Creamos entrada en NVRAM
2700ogNvramAddEntry refind /EFI/refind/grubx64.efi
2701# La ponemos en el segundo lugar del orden de arranque
2702NUMENTRY=$(efibootmgr |awk '{ if ($2=="refind") print substr($1,5,4)}')
2703NEWORDER="$(ogNvramGetOrder|awk -v NEW="$NUMENTRY" '{ gsub(",", " "); printf "%x %x %s\n",  $1 ,NEW, substr($0, index($0,$2)) }')"
2704ogNvramSetOrder $NEWORDER
2705
2706# Para la configuración del ogLive
2707ogMountCache &>/dev/null
2708if [ $? -eq 0 ]; then
2709    # Detectamos si hay ogLive
2710    CACHEDEVICE=$(ogDiskToDev $(ogFindCache))
2711    OGLIVE=$(find $OGCAC/boot -name ogvmlinuz|head -1)
2712    # Obtenemos parametros del kernel y sustituimos root
2713    # La línea de opciones no puede contener la cadena initrd.
2714    CMDLINE="$(cat /proc/cmdline|sed -e 's/^.*ogvmlinuz.efi //g' -e 's/^.*ogvmlinuz //g' -e 's|root=/dev/[a-z]* ||g' \
2715                     -e 's/ogupdateinitrd=[a-z]* //g')"
2716    CMDLINE="root=$CACHEDEVICE ${CMDLINE#*ogvmlinuz}"
2717
2718    # Icono para la entrada de menú
2719    OGICON=$(ls $OGLIB/refind/icons/so_opengnsys.png 2>/dev/null)
2720    [ "$OGICON" == "" ] && OGICON="${EFIDIR}/refind/icons/os_unknown.png"
2721    cp "$OGICON" "$OGCAC/.VolumeIcon.png"
2722fi
2723
2724# Configuramos rEFInd si es necesario
2725CFGFILE="${EFIDIR}/refind/refind.conf"
2726if [ "$CONFIG" == "TRUE" ]; then
2727    echo -e "\n\n# Configuración OpenGnsys" >> $CFGFILE
2728    # Excluimos dispositivos distintos de ESP y CACHE
2729    DEVICES=$(blkid -s PARTUUID |awk -v D=$EFIDEVICE -v C=$CACHEDEVICE '$1!=D":" && $1!=C":"  {gsub(/PARTUUID=/,"");gsub(/"/,"");   aux = aux" "$2","} END {print aux}')
2730    echo "dont_scan_volumes $DEVICES" >> $CFGFILE
2731    # Excluimos en la ESP los directorios de los sistemas operativos
2732    echo "dont_scan_dirs EFI/microsoft,EFI/ubuntu,EFI/grub" >> $CFGFILE
2733    echo "use_graphics_for osx,linux,windows" >> $CFGFILE
2734    echo "showtools reboot, shutdown" >> $CFGFILE
2735
2736    # Configuramos ogLive
2737    if [ "$OGLIVE" != "" ]; then
2738        # Cambiamos nombre de kernel e initrd para que lo detecte refind
2739        OGLIVEDIR="$(dirname  $OGLIVE)"
2740        cp "$OGLIVE" "${OGLIVE}.efi"
2741        cp "$OGLIVEDIR/oginitrd.img" "$OGLIVEDIR/initrd.img"
2742
2743        # Incluimos el directorio de ogLive.
2744        echo "also_scan_dirs +,boot/$(basename $OGLIVEDIR)" >> $CFGFILE
2745        # Fichero de configuración de refind para kernel de linux.
2746        LNXCFGFILE="$OGLIVEDIR/refind_linux.conf"
2747        echo "\"OpenGnsys Live\" \"$CMDLINE\"" > $LNXCFGFILE
2748
2749        # Ponemos ogLive como la entrada por defecto
2750        NUMENTRY=$(ls -d $EFIDIR/Part-??-??|wc -l)
2751        echo "default_selection $((NUMENTRY+1))" >> $CFGFILE
2752    fi
2753else
2754    # Renombramos la configuración por defecto
2755    mv $CFGFILE ${CFGFILE}.auto
2756
2757    # Creamos nueva configuración
2758    echo "# Configuración OpenGnsys" >> $CFGFILE
2759    echo "timeout 20" > $CFGFILE
2760    echo "showtools reboot, shutdown" >> $CFGFILE
2761    echo -e "scanfor manual\n" >> $CFGFILE
2762    # Configuración para sistemas restaurados con OpenGnsys
2763    for DIR in $(ls -d /mnt/sda1/EFI/Part-*-* 2>/dev/null); do
2764        echo "menuentry \"${DIR##*/}\" {" >> $CFGFILE
2765        echo "    loader /EFI/${DIR##*/}/Boot/ogloader.efi" >> $CFGFILE
2766        [ -f $DIR/Boot/bootmgfw.efi ] && echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2767        [ -f $DIR/grubx64.efi ] && echo "    icon /EFI/refind/icons/os_linux.png" >> $CFGFILE
2768        echo "}" >> $CFGFILE
2769    done
2770    # Configuración ogLive
2771    if [ "$OGLIVE" != "" ]; then
2772        echo "menuentry \"OpenGnsys Live\" {" >> $CFGFILE
2773        echo "    volume CACHE" >> $CFGFILE
2774        echo "    ostype Linux" >> $CFGFILE
2775        echo "    loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE
2776        echo "    initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE
2777        echo "    options \"$CMDLINE\"" >> $CFGFILE
2778        echo "}" >> $CFGFILE
2779
2780        # Ponemos ogLive como la entrada por defecto
2781        sed -i '1 i\default_selection "OpenGnsys Live"' $CFGFILE
2782    fi
2783fi
2784}
Note: See TracBrowser for help on using the repository browser.