source: client/engine/Boot.lib @ 202d6a3

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 202d6a3 was 8b5283a, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#922 Fixing code cleanup: theCgLiveAdapter?.lib content is located in ogGrubInstall.

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