source: client/engine/Boot.lib @ 713af37

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

#953 ogGrubDefaultEntry: Fixes the bad substitution that did not force the condition to match the whole line.

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