source: client/engine/Boot.lib @ befd4f9

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 befd4f9 was 67b3142, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #890 ogGrubInstallXx: grub's first stage finds grub.cfg correctly for computers no UEFI.

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