source: client/engine/Boot.lib @ 7da63e81

Last change on this file since 7da63e81 was b757c67, checked in by adv <adv@…>, 5 years ago

#935 #906 ogGrub4dosInstallMbr(): new function to install grub4dos on the MSDOS disk MBR

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