source: client/engine/Boot.lib @ 9c9de82

Last change on this file since 9c9de82 was 2150f01, checked in by Irina Gómez <irinagomez@…>, 3 years ago

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

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