source: client/engine/Boot.lib @ fc26e73

configure-oglivelgromero-new-oglivemainmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineoglive-ipv6test-python-scriptsticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since fc26e73 was 6be9081, checked in by Irina Gómez <irinagomez@…>, 3 years ago

#1066 #1069 ogBootMbrGeneric creates the necessary hard drive signature for Windows (UEFI).

(equivalent to commit 2150f01).

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