source: client/engine/Boot.lib @ 2a44804

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

ogGrubHidePartitions and ogBurgHidePartitions: help messages are enhanced.

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