source: client/engine/Boot.lib

lgromero-new-oglive
Last change on this file was 9ba0344, checked in by Irina Gómez <irinagomez@…>, 10 months ago

ref #455 ogBoot: adds parameter so that the NVRAM entry for booting OS is included in the boot order

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