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

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 5fd45d1 was 5fd45d1, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #889 #890 Fix UEFI postconf: configureOs does not use ogFixBootSector for Windows. ogGrubInstall does not change boot order in NVRAM.

  • Property mode set to 100755
File size: 91.5 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=$(printf "Part-%02d-%02d" $DISK $PART)
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} --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} --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} --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} --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 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# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1489#@brief Borra en el grub las entradas para el inicio en una particion.
1490#@param 1 Numero de disco donde esta el grub
1491#@param 2 Numero de particion donde esta el grub
1492#@param 3 Numero del disco del que borramos las entradas
1493#@param 4 Numero de la particion de la que borramos las entradas
1494#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
1495#@return  (nada)
1496#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1497#@exception OG_ERR_FORMAT    Formato incorrecto.
1498#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1499#@version 1.1 Se generaliza la función para grub y burg
1500#@author  Irina Gomez, ETSII Universidad de Sevilla
1501#@date    2017-10-20
1502#*/ ##
1503
1504function ogBootLoaderDeleteEntry ()
1505{
1506    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
1507
1508    # Si se solicita, mostrar ayuda.
1509    if [ "$*" == "help" ]; then
1510        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1511        return
1512    fi
1513
1514    # Si el número de parámetros menos que 4 nos salimos
1515    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1516 
1517
1518    # Nombre de la función que llama a esta.
1519    FUNC="${FUNCNAME[@]:1}"
1520    FUNC="${FUNC%%\ *}"
1521
1522    # Archivo de configuracion del grub
1523    DIRMOUNT=$(ogMount $1 $2)
1524    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1525    case "$FUNC" in
1526        ogGrubDeleteEntry)
1527            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1528            ;;
1529        ogBurgDeleteEntry)
1530            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1531            ;;
1532        *)
1533            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1534            return $?
1535            ;;
1536    esac
1537
1538    # Dispositivo
1539    DEVICE=$(ogDiskToDev $3 $4)
1540
1541    # Error si no existe archivo del grub)
1542    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
1543
1544    # Numero de linea de cada entrada.
1545    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1546
1547    # Entradas que hay que borrar.
1548    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1549
1550    # Si no hay entradas para borrar me salgo con aviso
1551    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
1552
1553    # Recorremos el fichero del final hacia el principio.
1554    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1555    for ENTRY in $MENUENTRY; do
1556        # Comprobamos si hay que borrar la entrada.
1557        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1558            let ENDENTRY=$ENDENTRY-1
1559            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1560        fi
1561
1562        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1563        ENDENTRY=$ENTRY
1564    done
1565}
1566
1567#/**
1568#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1569#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1570#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1571#@param   int_disk_SecondStage     
1572#@param   int_part_SecondStage     
1573#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1574#@return 
1575#@exception OG_ERR_FORMAT    Formato incorrecto.
1576#@exception OG_ERR_PARTITION  Partición no soportada
1577#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1578#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1579#@date    2017-06-23
1580#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1581#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1582#@date    2018-01-21
1583#@version 1.1.0 - Refactorizar fichero de configuacion
1584#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1585#@date    2018-01-24
1586#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1587#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1588#@date    2018-07-05
1589#@version 1.1.1 - UEFI: Es necesario grub.cfg para detectar parametros del kernel. Si no existe se recupera backup temporalmente (ticket #802 #890)
1590#@author  Irina Gomez, ETSII Universidad de Sevilla
1591#@date    2019-03-13
1592#*/ ##
1593
1594function ogBurgInstallMbr ()
1595{
1596 
1597# Variables locales.
1598local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG RECOVERBACKUP
1599
1600# Si se solicita, mostrar ayuda.
1601if [ "$*" == "help" ]; then
1602    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1603           "$FUNCNAME 1 1 FALSE " \
1604           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1605    return
1606fi 
1607
1608# Error si no se reciben 2 parametros.
1609[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1610
1611
1612DISK=$1; PART=$2;
1613CHECKOS=${3:-"FALSE"}
1614KERNELPARAM=$4
1615BACKUPNAME=".backup.og"
1616
1617#Error si no es linux.
1618ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1619
1620
1621#La primera etapa del grub se fija en el primer disco duro
1622FIRSTSTAGE=$(ogDiskToDev 1)
1623
1624#localizar disco segunda etapa del grub
1625SECONDSTAGE=$(ogMount $DISK $PART)
1626
1627# prepara el directorio principal de la segunda etapa (y copia los binarios)
1628[ -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)
1629
1630#Copiamos el tema
1631mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1632cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
1633
1634#Localizar directorio segunda etapa del grub   
1635#PREFIXSECONDSTAGE="/boot/burg/"
1636
1637# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1638if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1639then
1640    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1641    then
1642        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1643        return $?
1644    fi
1645fi
1646
1647# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1648
1649#llamada a updateBootCache para que aloje la primera fase del ogLive
1650updateBootCache
1651
1652# Si no existe el fichero grub.cfg pero sí el backup lo recupero (para UEFI)
1653if ogIsEfiActive && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]; then
1654    [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] || mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
1655    RECOVERYBACKUP=TRUE
1656fi
1657
1658
1659#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1660echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1661echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1662
1663
1664#Preparar configuración segunda etapa: crear ubicacion
1665mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1666
1667#Preparar configuración segunda etapa: crear cabecera del fichero
1668#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1669
1670FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1671
1672#/* ## (comentario Dogygen)
1673cat > "$FILECFG" << EOF
1674
1675set theme_name=OpenGnsys
1676set gfxmode=1024x768
1677
1678
1679set locale_dir=(\$root)/boot/burg/locale
1680
1681set default=0
1682set timeout=25
1683set lang=es
1684
1685
1686insmod ext2
1687insmod gettext
1688
1689
1690
1691
1692if [ -s \$prefix/burgenv ]; then
1693  load_env
1694fi
1695
1696
1697
1698if [ \${prev_saved_entry} ]; then
1699  set saved_entry=\${prev_saved_entry}
1700  save_env saved_entry
1701  set prev_saved_entry=
1702  save_env prev_saved_entry
1703  set boot_once=true
1704fi
1705
1706function savedefault {
1707  if [ -z \${boot_once} ]; then
1708    saved_entry=\${chosen}
1709    save_env saved_entry
1710  fi
1711}
1712function select_menu {
1713  if menu_popup -t template_popup theme_menu ; then
1714    free_config template_popup template_subitem menu class screen
1715    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1716    save_env theme_name
1717    menu_refresh
1718  fi
1719}
1720
1721function toggle_fold {
1722  if test -z $theme_fold ; then
1723    set theme_fold=1
1724  else
1725    set theme_fold=
1726  fi
1727  save_env theme_fold
1728  menu_refresh
1729}
1730function select_resolution {
1731  if menu_popup -t template_popup resolution_menu ; then
1732    menu_reload_mode
1733    save_env gfxmode
1734  fi
1735}
1736
1737
1738if test -f \${prefix}/themes/\${theme_name}/theme ; then
1739  insmod coreui
1740  menu_region.text
1741  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1742  load_config \${prefix}/themes/conf.d/10_hotkey   
1743  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1744  insmod vbe
1745  insmod png
1746  insmod jpeg
1747  set gfxfont="Unifont Regular 16"
1748  menu_region.gfx
1749  vmenu resolution_menu
1750  controller.ext
1751fi
1752
1753
1754EOF
1755#*/ ## (comentario Dogygen)
1756
1757#Preparar configuración segunda etapa: crear entrada del sistema operativo
1758grubSyntax "$KERNELPARAM" >> "$FILECFG"
1759
1760# Si hemos recuperado el backup del grub, volvemos a la situación original
1761[ "$RECOVERYBACKUP" == TRUE ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
1762
1763#Instalar el burg
1764burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1765}
1766
1767#/**
1768# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1769#@brief ver ogBootLoaderDefaultEntry
1770#@see ogBootLoaderDefaultEntry
1771#*/ ##
1772function ogGrubDefaultEntry ()
1773{
1774    # Si se solicita, mostrar ayuda.
1775    if [ "$*" == "help" ]; then
1776        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1777               "$FUNCNAME 1 6 1 1"
1778        return
1779    fi
1780    ogBootLoaderDefaultEntry $@
1781    return $?
1782}
1783
1784#/**
1785# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1786#@brief ver ogBootLoaderDefaultEntry
1787#@see ogBootLoaderDefaultEntry
1788#*/ ##
1789function ogBurgDefaultEntry ()
1790{
1791    # Si se solicita, mostrar ayuda.
1792    if [ "$*" == "help" ]; then
1793        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1794               "$FUNCNAME 1 6 1 1"
1795        return
1796    fi
1797    ogBootLoaderDefaultEntry $@
1798    return $?
1799}
1800
1801#/**
1802# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1803#@brief   Configura la entrada por defecto de Burg
1804#@param   int_disk_SecondStage     
1805#@param   int_part_SecondStage     
1806#@param   int_disk_default_entry
1807#@param   int_part_default_entry
1808#@return 
1809#@exception OG_ERR_FORMAT    Formato incorrecto.
1810#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1811#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1812#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1813#@version 1.1.0 - Define la entrada por defecto del Burg
1814#@author  Irina Gomez, ETSII Universidad de Sevilla
1815#@date    2017-08-09
1816#@version 1.1 Se generaliza la función para grub y burg
1817#@author  Irina Gomez, ETSII Universidad de Sevilla
1818#@date    2018-01-04
1819#*/ ##
1820function ogBootLoaderDefaultEntry ()
1821{
1822
1823# Variables locales.
1824local PART CFGFILE DEFAULTENTRY MSG
1825
1826# Si se solicita, mostrar ayuda.
1827if [ "$*" == "help" ]; then
1828    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
1829    return
1830fi 
1831
1832# Nombre de la función que llama a esta.
1833FUNC="${FUNCNAME[@]:1}"
1834FUNC="${FUNC%%\ *}"
1835
1836# Error si no se reciben 3 parametros.
1837[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1838
1839# Error si no puede montar sistema de archivos.
1840DIRMOUNT=$(ogMount $1 $2) || return $?
1841
1842# Comprobamos que exista fichero de configuración
1843# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1844case "$FUNC" in
1845    ogGrubDefaultEntry)
1846        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1847        ;;
1848    ogBurgDefaultEntry)
1849        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1850        ;;
1851    *)
1852        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1853        return $?
1854        ;;
1855esac
1856
1857# Error si no existe archivo de configuración
1858[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1859
1860# Dispositivo
1861DEVICE=$(ogDiskToDev $3 $4)
1862
1863# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1864DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1865
1866# Si no hay entradas para borrar me salgo con aviso
1867[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
1868
1869# Número de la de linea por defecto en el menú de usuario
1870MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1871# Las líneas empiezan a contar desde cero
1872let MENUENTRY=$MENUENTRY-1
1873sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1874MSG="MSG_HELP_$FUNC"
1875echo "${!MSG%%\.}: $@"
1876}
1877
1878#/**
1879# ogGrubOgliveDefaultEntry num_disk num_part
1880#@brief ver ogBootLoaderOgliveDefaultEntry
1881#@see ogBootLoaderOgliveDefaultEntry
1882#*/ ##
1883function ogGrubOgliveDefaultEntry ()
1884{
1885    # Si se solicita, mostrar ayuda.
1886    if [ "$*" == "help" ]; then
1887        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1888               "$FUNCNAME 1 6"
1889        return
1890    fi
1891    ogBootLoaderOgliveDefaultEntry $@
1892    return $?
1893}
1894
1895#/**
1896# ogBurgOgliveDefaultEntry num_disk num_part
1897#@brief ver ogBootLoaderOgliveDefaultEntry
1898#@see ogBootLoaderOgliveDefaultEntry
1899#*/ ##
1900function ogBurgOgliveDefaultEntry ()
1901{
1902    # Si se solicita, mostrar ayuda.
1903    if [ "$*" == "help" ]; then
1904        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1905               "$FUNCNAME 1 6"
1906        return
1907    fi
1908    ogBootLoaderOgliveDefaultEntry $@
1909    return $?
1910}
1911
1912#/**
1913# ogBootLoaderOgliveDefaultEntry
1914#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1915#@param   int_disk_SecondStage     
1916#@param   int_part_SecondStage     
1917#@return 
1918#@exception OG_ERR_FORMAT    Formato incorrecto.
1919#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1920#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1921#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1922#@version 1.1.0 - Primeras pruebas con Burg
1923#@author  Irina Gomez, ETSII Universidad de Sevilla
1924#@date    2017-08-09
1925#@version 1.1 Se generaliza la función para grub y burg
1926#@author  Irina Gomez, ETSII Universidad de Sevilla
1927#@date    2018-01-04
1928#*/ ##
1929function  ogBootLoaderOgliveDefaultEntry ()
1930{
1931
1932# Variables locales.
1933local FUNC PART CFGFILE NUMENTRY MSG
1934
1935# Si se solicita, mostrar ayuda.
1936if [ "$*" == "help" ]; then
1937    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
1938    return
1939fi 
1940
1941# Nombre de la función que llama a esta.
1942FUNC="${FUNCNAME[@]:1}"
1943FUNC="${FUNC%%\ *}"
1944
1945# Error si no se reciben 2 parametros.
1946[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1947
1948# Error si no puede montar sistema de archivos.
1949PART=$(ogMount $1 $2) || return $?
1950# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1951case "$FUNC" in
1952    ogGrubOgliveDefaultEntry)
1953        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1954        ;;
1955    ogBurgOgliveDefaultEntry)
1956        CFGFILE="$PART/boot/burg/burg.cfg"
1957        ;;
1958    *)
1959        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1960        return $?
1961        ;;
1962esac
1963
1964# Comprobamos que exista fichero de configuración
1965[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1966
1967# Detectamos cual es la entrada de ogLive
1968NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
1969
1970# Si no existe entrada de ogLive nos salimos
1971[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
1972
1973let NUMENTRY=$NUMENTRY-1
1974sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
1975
1976MSG="MSG_HELP_$FUNC"
1977echo "${!MSG%%\.}: $@"
1978}
1979
1980
1981#/**
1982# ogGrubSetTheme num_disk num_part str_theme
1983#@brief ver ogBootLoaderSetTheme
1984#@see ogBootLoaderSetTheme
1985#*/ ##
1986function ogGrubSetTheme ()
1987{
1988    # Si se solicita, mostrar ayuda.
1989    if [ "$*" == "help" ]; then
1990        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1991               "$FUNCNAME 1 4 ThemeBasic"\
1992               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1993        return
1994    fi
1995    ogBootLoaderSetTheme $@
1996    return $?
1997}
1998
1999#/**
2000# ogBurgSetTheme num_disk num_part str_theme
2001#@brief ver ogBootLoaderSetTheme
2002#@see ogBootLoaderSetTheme
2003#*/ ##
2004function ogBurgSetTheme  ()
2005{
2006    # Si se solicita, mostrar ayuda.
2007    if [ "$*" == "help" ]; then
2008        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
2009               "$FUNCNAME 1 4 ThemeBasic" \
2010               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2011        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
2012               
2013        return
2014    fi
2015    ogBootLoaderSetTheme $@
2016    return $?
2017}
2018
2019
2020#/**
2021# ogRefindSetTheme int_ndiskESP int_partitionESP str_theme
2022#@brief ver ogBootLoaderSetTheme
2023#@see ogBootLoaderSetTheme
2024#*/ ##
2025function ogRefindSetTheme () {
2026    local PART DIRTHEME CFGFILE
2027    # Si se solicita, mostrar ayuda.
2028    if [ "$*" == "help" ]; then
2029        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskESP int_partitionESP str_themeName" \
2030               "$FUNCNAME 1 1 ThemeBasic"
2031        echo -e "\nThemes in $OGLIB/refind:\n$(ls $OGLIB/refind/themes/)"
2032
2033        return
2034    fi
2035
2036    PART=$(ogMount $1 $2) || return $?
2037    DIRTHEME="$PART/EFI/refind/themes"
2038    CFGFILE="$PART/EFI/refind/refind.conf"
2039
2040    # Para utilizar ogBootLoaderSetTheme es necesario la entrada set theme_name
2041    if [ -f $CFGFILE ]; then
2042        sed -i '/showtools/i\set theme_name=none' $CFGFILE
2043    else
2044        ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2045    fi
2046    # Creamos el directorio para los temas
2047    [ -d $DIRTHEME ] || mkdir $DIRTHEME
2048
2049    ogBootLoaderSetTheme $@
2050    return $?
2051}
2052
2053
2054#/**
2055# ogBootLoaderSetTheme
2056#@brief   asigna un tema al BURG
2057#@param   int_disk_SecondStage     
2058#@param   int_part_SecondStage 
2059#@param   str_theme_name   
2060#@return 
2061#@exception OG_ERR_FORMAT    Formato incorrecto.
2062#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2063#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg refind.conf.
2064#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2065#@exception OG_ERR_NOTFOUND  Fichero de configuración del tema no encontrado: theme.conf (sólo refind).
2066#@note    El tema debe situarse en OGLIB/BOOTLOADER/themes
2067#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2068#@author  Antonio J. Doblas Viso. Universidad de Malaga
2069#@date    2018-01-24
2070#@version 1.1.1 - Soporta rEFInd (ticket #802 #888).
2071#@author  Irina Gomez. Universidad de Sevilla
2072#@date    2019-03-22
2073#*/ ##
2074function  ogBootLoaderSetTheme ()
2075{
2076
2077# Variables locales.
2078local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG NEWTHEMECFG
2079
2080# Si se solicita, mostrar ayuda.
2081if [ "$*" == "help" ]; then
2082    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme"
2083    return   
2084fi
2085 
2086
2087NEWTHEME="$3"
2088
2089# Nombre de la función que llama a esta.
2090FUNC="${FUNCNAME[@]:1}"
2091FUNC="${FUNC%%\ *}"
2092
2093
2094
2095# Error si no se reciben 3 parametros.
2096[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
2097
2098# Error si no puede montar sistema de archivos.
2099PART=$(ogMount $1 $2) || return $?
2100# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme.
2101case "$FUNC" in
2102    ogGrubSetTheme)
2103        BOOTLOADER="grug"
2104        BOOTLOADERDIR="boot/grubMBR"
2105        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2106        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
2107        return $?               
2108        ;;
2109    ogBurgSetTheme)
2110        BOOTLOADER="burg"
2111        BOOTLOADERDIR="boot/burg"
2112        CFGFILE="$PART/boot/burg/burg.cfg"       
2113        ;;
2114    ogRefindSetTheme)
2115        BOOTLOADER="refind"
2116        BOOTLOADERDIR="EFI/refind"
2117        CFGFILE="$PART/EFI/refind/refind.conf"
2118        ;;
2119    *)
2120        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
2121        return $?
2122        ;;
2123esac
2124
2125# Comprobamos que exista fichero de configuración
2126[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2127
2128# Detectamos cual es el tema asignado
2129THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
2130# Si no existe entrada de theme_name  nos salimos
2131[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
2132
2133#Actualizamos el tema del servidor a la particion
2134if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
2135        # Para refind es necesario que exista theme.conf en el directorio del tema.
2136        if [ "$BOOTLOADER" == "refind" ]; then
2137            NEWTHEMECFG="$OGLIB/$BOOTLOADER/themes/$NEWTHEME/theme.conf"
2138            [ -f $NEWTHEMECFG ] || ogRaiserError $OG_ERR_NOTFOUND "theme.conf" || return $?
2139            grep -v "^#" $NEWTHEMECFG >> $CFGFILE
2140            # eliminamos "set theme" es de grub y no de refind
2141            sed -i '/theme_name/d' $CFGFILE
2142        fi
2143        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/$BOOTLOADERDIR/themes/
2144fi
2145
2146#Verificamos que el tema esta en la particion
2147if ! [ -d $PART/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
2148                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/$BOOTLOADERDIR/themes/" || return $?
2149fi
2150
2151#Cambiamos la entrada el fichero de configuración.
2152sed --regexp-extended -i  s/"set theme_name=$THEME"/"set theme_name=$NEWTHEME"/g $CFGFILE
2153
2154
2155}
2156
2157#/**
2158# ogGrubSetAdminKeys num_disk num_part str_theme
2159#@brief ver ogBootLoaderSetTheme
2160#@see ogBootLoaderSetTheme
2161#*/ ##
2162function ogGrubSetAdminKeys ()
2163{
2164    # Si se solicita, mostrar ayuda.
2165    if [ "$*" == "help" ]; then
2166        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2167               "$FUNCNAME 1 4 FALSE "\
2168               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2169        return
2170    fi
2171    ogBootLoaderSetAdminKeys $@
2172    return $?
2173}
2174
2175#/**
2176# ogBurgSetAdminKeys num_disk num_part str_bolean
2177#@brief ver ogBootLoaderSetAdminKeys
2178#@see ogBootLoaderSetAdminKeys
2179#*/ ##
2180function ogBurgSetAdminKeys  ()
2181{
2182    # Si se solicita, mostrar ayuda.
2183    if [ "$*" == "help" ]; then
2184        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2185               "$FUNCNAME 1 4 TRUE" \
2186               "$FUNCNAME \$(ogFindCache) FALSE"               
2187        return
2188    fi
2189    ogBootLoaderSetAdminKeys $@
2190    return $?
2191}
2192
2193
2194
2195#/**
2196# ogBootLoaderSetAdminKeys
2197#@brief   Activa/Desactica las teclas de administracion
2198#@param   int_disk_SecondStage     
2199#@param   int_part_SecondStage 
2200#@param   Boolean TRUE/FALSE   
2201#@return 
2202#@exception OG_ERR_FORMAT    Formato incorrecto.
2203#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2204#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2205#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2206#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2207#@author  Antonio J. Doblas Viso. Universidad de Malaga
2208#@date    2018-01-24
2209#*/ ##
2210function  ogBootLoaderSetAdminKeys ()
2211{
2212
2213# Variables locales.
2214local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2215
2216# Si se solicita, mostrar ayuda.
2217if [ "$*" == "help" ]; then
2218    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2219    return   
2220fi
2221 
2222
2223# Nombre de la función que llama a esta.
2224FUNC="${FUNCNAME[@]:1}"
2225FUNC="${FUNC%%\ *}"
2226
2227
2228# Error si no se reciben 2 parametros.
2229[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2230
2231# Error si no puede montar sistema de archivos.
2232PART=$(ogMount $1 $2) || return $?
2233# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2234case "$FUNC" in
2235    ogGrubSetAdminKeys)
2236        BOOTLOADER="grug"
2237        BOOTLOADERDIR="grubMBR"
2238        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2239        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2240        return $?       
2241        ;;
2242    ogBurgSetAdminKeys)
2243        BOOTLOADER="burg"
2244        BOOTLOADERDIR="burg"
2245        CFGFILE="$PART/boot/burg/burg.cfg"       
2246        ;;
2247    *)
2248        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2249        return $?
2250        ;;
2251esac
2252
2253
2254# Comprobamos que exista fichero de configuración
2255[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2256
2257
2258case "$3" in
2259        true|TRUE)
2260                [ -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
2261        ;;
2262        false|FALSE)
2263                [ -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
2264        ;;     
2265        *)
2266           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2267        return $?
2268    ;; 
2269esac
2270}
2271
2272
2273
2274#/**
2275# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
2276#@brief ver ogBootLoaderSetTimeOut
2277#@see ogBootLoaderSetTimeOut
2278#*/ ##
2279function ogGrubSetTimeOut ()
2280{
2281    # Si se solicita, mostrar ayuda.
2282    if [ "$*" == "help" ]; then
2283        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2284               "$FUNCNAME 1 4 50 "\
2285               "$FUNCNAME \$(ogFindCache) 50"
2286        return
2287    fi
2288    ogBootLoaderSetTimeOut $@
2289    return $?
2290}
2291
2292#/**
2293# ogBurgSetTimeOut num_disk num_part str_bolean
2294#@brief ver ogBootLoaderSetTimeOut
2295#@see ogBootLoaderSetTimeOut
2296#*/ ##
2297function ogBurgSetTimeOut ()
2298{
2299    # Si se solicita, mostrar ayuda.
2300    if [ "$*" == "help" ]; then
2301        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2302               "$FUNCNAME 1 4 50" \
2303               "$FUNCNAME \$(ogFindCache) 50"               
2304        return
2305    fi
2306    ogBootLoaderSetTimeOut $@
2307    return $?
2308}
2309
2310
2311
2312#/**
2313# ogBootLoaderSetTimeOut
2314#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2315#@param   int_disk_SecondStage     
2316#@param   int_part_SecondStage 
2317#@param   int_timeout_seconds   
2318#@return 
2319#@exception OG_ERR_FORMAT    Formato incorrecto.
2320#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2321#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2322#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2323#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2324#@author  Antonio J. Doblas Viso. Universidad de Malaga
2325#@date    2018-01-24
2326#*/ ##
2327function  ogBootLoaderSetTimeOut ()
2328{
2329
2330# Variables locales.
2331local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2332
2333# Si se solicita, mostrar ayuda.
2334if [ "$*" == "help" ]; then
2335    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut"
2336    return   
2337fi
2338 
2339ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2340
2341# Nombre de la función que llama a esta.
2342FUNC="${FUNCNAME[@]:1}"
2343FUNC="${FUNC%%\ *}"
2344
2345# Error si no se reciben 3 parametros.
2346[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2347
2348# Error si no puede montar sistema de archivos.
2349PART=$(ogMount $1 $2) || return $?
2350# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut.
2351case "$FUNC" in
2352    ogGrubSetTimeOut)
2353        BOOTLOADER="grug"
2354        BOOTLOADERDIR="grubMBR"
2355        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2356        ;;
2357    ogBurgSetTimeOut)
2358        BOOTLOADER="burg"
2359        BOOTLOADERDIR="burg"
2360        CFGFILE="$PART/boot/burg/burg.cfg"       
2361        ;;
2362    *)
2363        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut"
2364        return $?
2365        ;;
2366esac
2367
2368# Comprobamos que exista fichero de configuración
2369[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2370
2371# Asignamos el timeOut.
2372sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2373}
2374
2375
2376#/**
2377# ogGrubSetResolution num_disk num_part int_resolution
2378#@brief ver ogBootLoaderSetResolution
2379#@see ogBootLoaderSetResolution
2380#*/ ##
2381function ogGrubSetResolution ()
2382{
2383    # Si se solicita, mostrar ayuda.
2384    if [ "$*" == "help" ]; then
2385        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2386             "$FUNCNAME 1 4 1024x768" \
2387             "$FUNCNAME \$(ogFindCache) 1024x768" \
2388             "$FUNCNAME 1 4" 
2389        return
2390    fi
2391    ogBootLoaderSetResolution $@
2392    return $?
2393}
2394
2395#/**
2396# ogBurgSetResolution num_disk num_part str_bolean
2397#@brief ver ogBootLoaderSetResolution
2398#@see ogBootLoaderSetResolution
2399#*/ ##
2400function ogBurgSetResolution ()
2401 {
2402    # Si se solicita, mostrar ayuda.
2403    if [ "$*" == "help" ]; then
2404        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2405               "$FUNCNAME 1 4 1024x768" \
2406               "$FUNCNAME \$(ogFindCache) 1024x768" \
2407               "$FUNCNAME 1 4"               
2408        return
2409    fi
2410    ogBootLoaderSetResolution $@
2411    return $?
2412}
2413
2414
2415
2416#/**
2417# ogBootLoaderSetResolution
2418#@brief   Define la resolucion que usuara el thema del gestor de arranque
2419#@param   int_disk_SecondStage     
2420#@param   int_part_SecondStage 
2421#@param   str_resolution (Opcional)   
2422#@return 
2423#@exception OG_ERR_FORMAT    Formato incorrecto.
2424#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2425#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2426#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2427#@author  Antonio J. Doblas Viso. Universidad de Malaga
2428#@date    2018-01-24
2429#*/ ##
2430function  ogBootLoaderSetResolution ()
2431{
2432
2433# Variables locales.
2434local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2435
2436# Si se solicita, mostrar ayuda.
2437if [ "$*" == "help" ]; then
2438    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution"
2439    return   
2440fi
2441
2442
2443# Nombre de la función que llama a esta.
2444FUNC="${FUNCNAME[@]:1}"
2445FUNC="${FUNC%%\ *}"
2446
2447
2448# Error si no se reciben 2 parametros.
2449[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2450
2451# Error si no puede montar sistema de archivos.
2452PART=$(ogMount $1 $2) || return $?
2453# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution.
2454case "$FUNC" in
2455    ogGrubSetResolution)
2456        BOOTLOADER="grug"
2457        BOOTLOADERDIR="grubMBR"
2458        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2459        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2460        return $?     
2461        ;;
2462    ogBurgSetResolution)
2463        BOOTLOADER="burg"
2464        BOOTLOADERDIR="burg"
2465        CFGFILE="$PART/boot/burg/burg.cfg"       
2466        ;;
2467    *)
2468        ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution"
2469        return $?
2470        ;;
2471esac
2472
2473DEFAULTRESOLUTION=1024x768
2474
2475# Comprobamos que exista fichero de configuración
2476[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2477
2478#controlar variable a consierar vga (default template) o video (menu)
2479#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2480if [ $# -eq 2 ] ; then 
2481        if [ -n $video ]; then
2482                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2483        fi
2484        if [ -n $vga ] ; then
2485        case "$vga" in
2486                788|789|814)
2487                        NEWRESOLUTION=800x600
2488                        ;;
2489                791|792|824)
2490                        NEWRESOLUTION=1024x768
2491                        ;;
2492                355)
2493                        NEWRESOLUTION=1152x864
2494                        ;;
2495                794|795|829)
2496                        NEWRESOLUTION=1280x1024
2497                        ;;
2498        esac
2499        fi
2500fi
2501
2502if [ $# -eq 3 ] ; then
2503        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2504        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"
2505fi
2506
2507# Si no existe NEWRESOLUCION  asignamos la defaulT
2508[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2509
2510#Cambiamos la entrada el fichero de configuración.
2511sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2512}
2513
2514#         ogRefindInstall bool_autoconfig
2515#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2516#@param   bolean_Check__auto_config   true | false[default]
2517#@return
2518#@exception OG_ERR_FORMAT    Formato incorrecto.
2519#@exception OG_ERR_NOTFOUND  No se encuentra la partición ESP.
2520#@exception OG_ERR_NOTFOUND  No se encuentra shimx64.efi.signed.
2521#@exception OG_ERR_NOTFOUND  No se encuentra refind-install o refind en OGLIB
2522#@exception OG_ERR_PARTITION No se puede montar la partición ESP.
2523#@note    Refind debe estar instalado en el ogLive o compartido en OGLIB
2524#@version 1.1.0 - Primeras pruebas.
2525#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2526#@date    2017-06-26
2527#@version 1.1.1 - Usa refind-install. Obtiene partición con ogGetEsp. Configura Part-X-Y y ogLive.
2528#@author  Irina Gomez. Universidad de Sevilla.
2529#@date    2019-03-22
2530#*/ ##
2531function ogRefindInstall () {
2532# Variables locales.
2533local CONFIG EFIDISK EFIPART EFIDEVICE EFIMNT EFIDIR SHIM DIRREFIND CFGFILE DIR OGLIVE CMDLINE
2534
2535# Si se solicita, mostrar ayuda.
2536if [ "$*" == "help" ]; then
2537    ogHelp "$FUNCNAME" "$FUNCNAME boolean_autoconfig " \
2538           "$FUNCNAME 1 TRUE"
2539    return
2540fi
2541
2542# Recogemos parametros
2543CONFIG=${1:-"FALSE"}
2544
2545read -e EFIDISK EFIPART  <<< $(ogGetEsp)
2546EFIDEVICE=$(ogDiskToDev $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_NOTFOUND "ESP" || return $?
2547EFIMNT=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR mount ESP" || return $?
2548EFIDIR="$EFIMNT/EFI"
2549[ -d $EFIDIR ] || mkdir $EFIDIR
2550
2551# Instalamos rEFInd. Con refind-install o copiandolo del OGLIB
2552if which refind-install &>/dev/null; then
2553    # Comprobamos que exista shimx64
2554    SHIM=$(ogGetPath /usr/lib/shim/shimx64.efi.signed)
2555    [ "$SHIM" == "" ] && return $(ogRaiseError $OG_ERR_NOTFOUND "shimx64.efi.signed")
2556
2557    refind-install --yes --alldrivers --usedefault $EFIDEVICE  --shim $SHIM
2558
2559    # Cambiamos el nombre del directorio
2560    [ -d $EFIDIR/refind ] && rm -rf $EFIDIR/refind
2561    mv $EFIDIR/BOOT  $EFIDIR/refind
2562
2563    # Desmontamos directorio temporal
2564    umount /tmp/refind_install
2565else
2566    DIRREFIND=$OGLIB/refind
2567    [ -d $DIRREFIND ] || ogRaiseError $OG_ERR_NOTFOUND "refind-install or $DIRREFIND" || return $?
2568    cp -r $DIRREFIND $EFIDIR
2569fi
2570
2571# Configuramos rEFInd si es necesario
2572if [ "$CONFIG" == "FALSE" ]; then
2573    # Renombramos la configuración por defecto
2574    mv  ${EFIDIR}/refind/refind.conf ${EFIDIR}/refind/refind.conf.auto
2575
2576    # Creamos nueva configuración
2577    CFGFILE="${EFIDIR}/refind/refind.conf"
2578    echo "timeout 20" > $CFGFILE
2579    echo "showtools reboot, shutdown" >> $CFGFILE
2580    echo -e "scanfor manual\n" >> $CFGFILE
2581    if [ -a ${EFIDIR}/Microsoft ]; then
2582        echo "menuentry \"Windows\" {" >> $CFGFILE
2583        echo "    loader /EFI/Microsoft/Boot/bootmgfw.efi" >> $CFGFILE
2584        echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2585        echo "}" >> $CFGFILE
2586    fi
2587    if [ -a ${EFIDIR}/ubuntu ]; then
2588        echo "menuentry \"Ubuntu\" {" >> $CFGFILE
2589        echo "    loader /EFI/ubuntu/grubx64.efi" >> $CFGFILE
2590        echo "    icon /EFI/refind/icons/os_ubuntu.png" >> $CFGFILE
2591        echo "}" >> $CFGFILE
2592    fi
2593    for DIR in $(ls -d /mnt/sda1/EFI/Part-*-* 2>/dev/null); do
2594        echo "menuentry \"${DIR##*/}\" {" >> $CFGFILE
2595        echo "    loader /EFI/${DIR##*/}/Boot/ogloader.efi" >> $CFGFILE
2596        [ -f $DIR/Boot/bootmgfw.efi ] && echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2597        [ -f $DIR/grubx64.efi ] && echo "    icon /EFI/refind/icons/os_linux.png" >> $CFGFILE
2598        echo "}" >> $CFGFILE
2599    done
2600    ogMountCache &>/dev/null
2601    OGLIVE=$(find $OGCAC -name ogvmlinuz|head -1)
2602    if [ "$OGLIVE" != "" ]; then
2603        read -e CACDISK CACPART <<< $(ogFindCache)
2604        # Obtenemos parametros del kernel y sustituimos root
2605        CMDLINE="$(cat /proc/cmdline)"
2606        CMDLINE="root=$(ogDiskToDev $CACDISK $CACPART) ${CMDLINE#*ogvmlinuz}"
2607        echo "menuentry \"OpenGnsys Client\" {" >> $CFGFILE
2608        echo "    volume CACHE" >> $CFGFILE
2609        echo "    ostype Linux" >> $CFGFILE
2610        echo "    loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE
2611        echo "    initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE
2612        echo "    options \"$CMDLINE\"" >> $CFGFILE
2613        echo "    icon /EFI/refind/icons/os_unknown.png" >> $CFGFILE
2614        echo "}" >> $CFGFILE
2615
2616        # Ponemos ogLive como la entrada por defecto
2617        sed -i '/showtools/i\default_selection "OpenGnsys Client"' $CFGFILE
2618    fi
2619fi
2620}
Note: See TracBrowser for help on using the repository browser.