source: client/engine/Boot.lib @ 1d1e06d

Last change on this file since 1d1e06d was 9fe0fe3, checked in by Irina Gómez <irinagomez@…>, 5 years ago

#841 Fixes bug in partitioning wizard when configure MBR: ogGetBootMbr function is created for detect MBR content and used in wizard.

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