source: client/engine/Boot.lib @ 5b809ba

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

#802 #890 ogGrubInstall includes option to secure boot.

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