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

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

#802 #890 ogGrubInstallMbr detects Windows loader en ESP and saves de ogbootloader into directory 'grub'·

  • Property mode set to 100755
File size: 90.8 KB
Line 
1#!/bin/bash
2#/**
3#@file    Boot.lib
4#@brief   Librería o clase Boot
5#@class   Boot
6#@brief   Funciones para arranque y post-configuración de sistemas de archivos.
7#@version 1.1.0
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogBoot int_ndisk int_nfilesys [str_kernel str_initrd str_krnlparams]
14#@brief   Inicia el proceso de arranque de un sistema de archivos.
15#@param   int_ndisk      nº de orden del disco
16#@param   int_nfilesys   nº de orden del sistema de archivos
17#@param   str_krnlparams parámetros de arranque del kernel (opcional)
18#@return  (activar el sistema de archivos).
19#@exception OG_ERR_FORMAT    Formato incorrecto.
20#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
21#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
22#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
23#@note    En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB.
24#@note    En Linux, debe arrancarse la partición del directorio \c /boot
25#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib 
26#@author  Antonio J. Doblas Viso, Universidad de Malaga
27#@date    2008-10-27
28#@version 0.9 - Adaptación para OpenGnSys.
29#@author  Ramon Gomez, ETSII Universidad de Sevilla
30#@date    2009-09-11
31#@version 1.0.4 - Soporta modo de arranque Windows (parámetro de inicio "winboot").
32#@author  Ramon Gomez, ETSII Universidad de Sevilla
33#@date    2012-04-12
34#@version 1.0.6 - Selección a partir de tipo de sistema operativo (en vez de S.F.) y arrancar Linux con /boot separado.
35#@author  Ramon Gomez, ETSII Universidad de Sevilla
36#@date    2015-06-05
37#@version 1.1.0 - Nuevo parámetro opcional con opciones de arranque del Kernel.
38#@author  Ramon Gomez, ETSII Universidad de Sevilla
39#@date    2015-07-15
40#@version 1.1.1 - UEFI: Permite iniciar linux recien instalados (ticket #802 #890)
41#@author  Irina Gomez, ETSII Universidad de Sevilla
42#@date    2019-03-13
43#*/ ##
44function ogBoot ()
45{
46# Variables locales.
47local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
48local EFIDISK EFIPART EFIDIR BOOTLABEL BOOTLOADER BOOTNO DIRGRUB b
49
50# Si se solicita, mostrar ayuda.
51if [ "$*" == "help" ]; then
52    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_kernel str_initrd str_kernelparams]" \
53           "$FUNCNAME 1 1" "$FUNCNAME 1 2 \"/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro\""
54    return
55fi
56# Error si no se reciben 2 o 3 parámetros.
57[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
58
59# Detectar tipo de sistema de archivos y montarlo.
60PART=$(ogDiskToDev $1 $2) || return $?
61TYPE=$(ogGetOsType $1 $2) || return $?
62# Error si no puede montar sistema de archivos.
63MNTDIR=$(ogMount $1 $2) || return $?
64
65case "$TYPE" in
66    Linux|Android)
67        # Si no se indican, obtiene los parámetros de arranque para Linux.
68        PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}"
69        # Si no existe y el UEFI buscar en particion ESP
70        [ -z "$PARAMS" ] && ogIsEfiActive && PARAMS="$(ogLinuxBootParameters $(ogGetEsp))"
71        # Si no existe, buscar sistema de archivo /boot en /etc/fstab.
72        if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then
73            # Localizar S.F. /boot en /etc/fstab del S.F. actual.
74            PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
75            # Montar S.F. de /boot.
76            MNTDIR=$(ogMount $PART) || return $?
77            # Buscar los datos de arranque.
78            PARAMS=$(ogLinuxBootParameters $PART) || exit $?
79        fi
80        read -e KERNEL INITRD APPEND <<<"$PARAMS"
81        # Si no hay kernel, no hay sistema operativo.
82        [ -n "$KERNEL" -a -e "$MNTDIR/$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
83        # Arrancar de partición distinta a la original.
84        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
85        # Comprobar tipo de sistema.
86        if ogIsEfiActive; then
87            # Comprobar si el Kernel está firmado.
88            if ! file -k "$MNTDIR/$KERNEL" | grep -q "EFI app"; then
89                ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)"
90                return $?
91            fi
92
93            # Borrar cargador guardado con la misma etiqueta.
94            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
95            BOOTLOADER="grubx64.efi"
96            # Obtener parcición EFI.
97            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
98            # TODO: Comprobamos que existe la BOOTLABEL, si no buscamos por sistema operativo
99            if [ "$(ogGetPath $EFIDISK $EFIPART EFI/$BOOTLABEL)" == "" ]; then
100                OSVERSION="$(ogGetOsVersion $1 $2)"
101                case $OSVERSION in
102                    *SUSE*)
103                       BOOTLABEL="opensuse"
104                       ;;
105                    *Fedora*)
106                       BOOTLABEL="fedora"
107                       ;;
108                    *Ubuntu*)
109                       BOOTLABEL="ubuntu"
110                       ;;
111                    *)
112                       ogRaiseError $OG_ERR_NOTFOUND "$EFIDISK $EFIPART Boot loader"; return $?
113                       ;;
114                esac
115            fi
116
117            # Crear orden de arranque (con unos valores por defecto).
118            BOOTNO=$(efibootmgr -v | awk -v L=$BOOTLABEL '{if ($2==L) print $1}')
119            for b in $BOOTNO; do
120                efibootmgr -B -b ${b:4:4} &>/dev/null
121            done
122            efibootmgr -C -d $(ogDiskToDev $EFIDISK) -p $EFIPART -L "$BOOTLABEL" -l "/EFI/$BOOTLABEL/$BOOTLOADER" &>/dev/null
123            # Marcar próximo arranque y reiniciar.
124            BOOTNO=$(efibootmgr -v | awk -v L="$BOOTLABEL" '{if ($2==L) print $1}')
125            [ -n "$BOOTNO" ] && efibootmgr -n ${BOOTNO:4:4} &>/dev/null
126            # Incluimos en el orden de arranque
127            BOOTORDER=$(efibootmgr | awk -v L="BootOrder:" '{if ($1==L) print $2}')
128            [[ $BOOTORDER =~ ${BOOTNO:4:4} ]] || efibootmgr -o $BOOTORDER,${BOOTNO:4:4}
129            reboot
130        else
131            # Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB.
132            kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
133            kexec -e &
134        fi
135        ;;
136    Windows)
137        # Comprobar tipo de sistema.
138        if ogIsEfiActive; then
139            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
140            # Obtener parcición EFI.
141            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
142            [ -n "$EFIPART" ] || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
143            EFIDIR=$(ogMount $EFIDISK $EFIPART) || exit $?
144            # Comprobar cargador (si no existe buscar por defecto en ESP).
145            #LOADER=$(ogGetPath $1 $2 /Boot/bootmgfw.efi)
146            LOADER=$(ogGetPath $EFIDIR/EFI/$BOOTLABEL/Boot/bootmgfw.efi)
147            [ -z "$LOADER" ] && BOOTLABEL=Microsoft && LOADER=$(ogGetPath $EFIDIR/EFI/Microsoft/Boot/bootmgfw.efi)
148            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)" || return $?
149            # El directorio se crea en la postconfiguración
150            ## Crear directorio para el cargador y copiar los ficheros.
151            #mkdir -p $EFIDIR/EFI/$BOOTLABEL
152            #cp -a $(dirname "$LOADER") $EFIDIR/EFI/$BOOTLABEL
153            # Borrar cargador guardado con la misma etiqueta.
154            BOOTNO=$(efibootmgr -v | awk -v L=$BOOTLABEL '{if ($2==L) print $1}')
155            [ -n "$BOOTNO" ] && efibootmgr -B -b ${BOOTNO:4:4}
156            # Crear orden de arranque (con unos valores por defecto).
157            efibootmgr -C -d $(ogDiskToDev $EFIDISK) -p $EFIPART -L "$BOOTLABEL" -l "/EFI/$BOOTLABEL/Boot/BOOTMGFW.EFI"
158            # Marcar próximo arranque y reiniciar.
159            BOOTNO=$(efibootmgr -v | awk -v L="$BOOTLABEL" '{if ($2==L) print $1}')
160            [ -n "$BOOTNO" ] && efibootmgr -n ${BOOTNO:4:4}
161            reboot
162        else
163            # Arranque BIOS: comprueba si hay un cargador de Windows.
164            for f in io.sys ntldr bootmgr; do
165                FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
166                [ -n "$FILE" ] && LOADER="$f"
167            done
168            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
169            if [ "$winboot" == "kexec" ]; then
170                # Modo de arranque en caliente (con kexec).
171                cp $OGLIB/grub4dos/* $MNTDIR    # */ (Comentario Doxygen)
172                kexec -l $MNTDIR/grub.exe --append=--config-file="root (hd$[$1-1],$[$2-1]); chainloader (hd$[$1-1],$[$2-1])/$LOADER; tpm --init"
173                kexec -e &
174            else
175                # Modo de arranque por reinicio (con reboot).
176                dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3
177                dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3
178                dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3
179                if  [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then
180                    ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot'
181                    ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*"
182                fi
183                # Activar la partición.
184                ogSetPartitionActive $1 $2
185                reboot
186            fi
187        fi
188        ;;
189    MacOS)
190        # Modo de arranque por reinicio.
191        # Nota: el cliente tiene que tener configurado correctamente Grub.
192        touch ${MNTDIR}/boot.mac &>/dev/null
193        reboot
194        ;;
195    GrubLoader)
196        # Reiniciar.
197        #reboot
198        ;;
199    *)  ogRaiseError $OG_ERR_NOTOS "$1 $2 ${TYPE:+($TYPE)}"
200        return $?
201        ;;
202esac
203}
204
205
206#/**
207#         ogGetWindowsName int_ndisk int_nfilesys
208#@brief   Muestra el nombre del equipo en el registro de Windows.
209#@param   int_ndisk      nº de orden del disco
210#@param   int_nfilesys   nº de orden del sistema de archivos
211#@return  str_name - nombre del equipo
212#@exception OG_ERR_FORMAT    Formato incorrecto.
213#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
214#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
215#@version 0.9 - Adaptación para OpenGnSys.
216#@author  Ramon Gomez, ETSII Universidad de Sevilla
217#@date    2009-09-23
218#*/ ##
219function ogGetWindowsName ()
220{
221# Variables locales.
222local MNTDIR
223
224# Si se solicita, mostrar ayuda.
225if [ "$*" == "help" ]; then
226    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
227           "$FUNCNAME 1 1  ==>  PRACTICA-PC"
228    return
229fi
230# Error si no se reciben 2 parámetros.
231[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
232
233# Montar el sistema de archivos.
234MNTDIR=$(ogMount $1 $2) || return $?
235
236# Obtener dato del valor de registro.
237ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
238}
239
240
241#/**
242#         ogLinuxBootParameters int_ndisk int_nfilesys
243#@brief   Muestra los parámetros de arranque de un sistema de archivos Linux.
244#@param   int_ndisk      nº de orden del disco
245#@param   int_nfilesys   nº de orden del sistema de archivos
246#@return  str_kernel str_initrd str_parameters ...
247#@exception OG_ERR_FORMAT    Formato incorrecto.
248#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
249#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
250#@warning Función básica usada por \c ogBoot
251#@version 0.9 - Primera adaptación para OpenGnSys.
252#@author  Ramon Gomez, ETSII Universidad de Sevilla
253#@date    2009-09-11
254#@version 0.9.2 - Soporta partición /boot independiente.
255#@author  Ramon Gomez, ETSII Universidad de Sevilla
256#@date    2010-07-20
257#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
258#@author  Ramon Gomez, ETSII Universidad de Sevilla
259#@date    2013-05-14
260#@version 1.0.6 - Detectar instalaciones sobre EFI.
261#@author  Ramon Gomez, ETSII Universidad de Sevilla
262#@date    2014-09-15
263#*/ ##
264function ogLinuxBootParameters ()
265{
266# Variables locales.
267local MNTDIR CONFDIR CONFFILE f
268
269# Si se solicita, mostrar ayuda.
270if [ "$*" == "help" ]; then
271    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
272           "$FUNCNAME 1 2  ==>  /vmlinuz-3.5.0-21-generic /initrd.img-3.5.0-21-generic root=/dev/sda2 ro splash"
273    return
274fi
275# Error si no se reciben 2 parámetros.
276[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
277
278# Detectar id. de tipo de partición y codificar al mnemonico.
279MNTDIR=$(ogMount $1 $2) || return $?
280
281# Fichero de configuración de GRUB.
282CONFDIR=$MNTDIR                               # Sistema de archivos de arranque (/boot).
283[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot   # Sist. archivos raíz con directorio boot.
284for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
285    [ -r $f ] && CONFFILE=$f
286done
287[ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
288
289# Toma del fichero de configuracion los valores del kernel, initrd
290#       y parámetros de arranque usando las cláusulas por defecto
291#       ("default" en GRUB1, "set default" en GRUB2)
292#       y los formatea para que sean compatibles con \c kexec .  */
293# /* (comentario Doxygen)
294awk 'BEGIN {cont=-1;}
295     $1~/^default$/     {sub(/=/," "); def=$2;}
296     $1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3;
297                                   if (def ~ /saved_entry/) def=0;
298                                 }
299     $1~/^(title|menuentry)$/ {cont++}
300     $1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; }
301     $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
302                                       kern=$2;
303                                       sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
304                                      } # /* (comentario Doxygen)
305                                    }
306     $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
307     END {if (kern!="") printf("%s %s %s", kern,init,app)}
308    ' $CONFFILE
309# */ (comentario Doxygen)
310}
311
312
313#/**
314#         ogSetWindowsName int_ndisk int_nfilesys str_name
315#@brief   Establece el nombre del equipo en el registro de Windows.
316#@param   int_ndisk      nº de orden del disco
317#@param   int_nfilesys   nº de orden del sistema de archivos
318#@param   str_name       nombre asignado
319#@return  (nada)
320#@exception OG_ERR_FORMAT     Formato incorrecto.
321#@exception OG_ERR_NOTFOUND   Disco o particion no corresponden con un dispositivo.
322#@exception OG_ERR_PARTITION  Tipo de partición desconocido o no se puede montar.
323#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
324#@version 0.9 - Adaptación a OpenGnSys.
325#@author  Ramon Gomez, ETSII Universidad de Sevilla
326#@date    2009-09-24
327#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
328#@author  Ramon Gomez, ETSII Universidad de Sevilla
329#@date    2013-03-20
330#*/ ##
331function ogSetWindowsName ()
332{
333# Variables locales.
334local PART MNTDIR NAME
335
336# Si se solicita, mostrar ayuda.
337if [ "$*" == "help" ]; then
338    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
339           "$FUNCNAME 1 1 PRACTICA-PC"
340    return
341fi
342# Error si no se reciben 3 parámetros.
343[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
344# Error si el nombre supera los 15 caracteres.
345[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
346
347# Montar el sistema de archivos.
348MNTDIR=$(ogMount $1 $2) || return $?
349
350# Asignar nombre.
351NAME="$3"
352
353# Modificar datos de los valores de registro.
354ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
355ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
356ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\HostName' "$NAME" 2>/dev/null
357ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
358ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
359ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV HostName' "$NAME" 2>/dev/null
360ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
361}
362
363
364#/**
365#         ogSetWinlogonUser int_ndisk int_npartition str_username
366#@brief   Establece el nombre de usuario por defecto en la entrada de Windows.
367#@param   int_ndisk      nº de orden del disco
368#@param   int_npartition nº de orden de la partición
369#@param   str_username   nombre de usuario por defecto
370#@return  (nada)
371#@exception OG_ERR_FORMAT    Formato incorrecto.
372#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
373#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
374#@version 0.9.2 - Adaptación a OpenGnSys.
375#@author  Ramon Gomez, ETSII Universidad de Sevilla
376#@date    2010-07-20
377#*/ ##
378function ogSetWinlogonUser ()
379{
380# Variables locales.
381local PART MNTDIR NAME
382
383# Si se solicita, mostrar ayuda.
384if [ "$*" == "help" ]; then
385    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
386           "$FUNCNAME 1 1 USUARIO"
387    return
388fi
389# Error si no se reciben 3 parámetros.
390[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
391
392# Montar el sistema de archivos.
393MNTDIR=$(ogMount $1 $2) || return $?
394
395# Asignar nombre.
396NAME="$3"
397
398# Modificar datos en el registro.
399ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
400}
401
402
403#/**
404#         ogBootMbrXP int_ndisk
405#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
406#@param   int_ndisk      nº de orden del disco
407#@return  salida del programa my-sys
408#@exception OG_ERR_FORMAT    Formato incorrecto.
409#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
410#@version 0.9 - Adaptación a OpenGnSys.
411#@author  Antonio J. Doblas Viso. Universidad de Málaga
412#@date    2009-09-24
413#*/ ##
414
415function ogBootMbrXP ()
416{
417# Variables locales.
418local DISK
419
420# Si se solicita, mostrar ayuda.
421if [ "$*" == "help" ]; then
422    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
423           "$FUNCNAME 1"
424    return
425fi
426# Error si no se recibe 1 parámetro.
427[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
428
429DISK="$(ogDiskToDev $1)" || return $?
430ms-sys -z -f $DISK
431ms-sys -m -f $DISK
432}
433
434
435#/**
436#         ogBootMbrGeneric int_ndisk
437#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
438#@param   int_ndisk      nº de orden del disco
439#@return  salida del programa my-sys
440#@exception OG_ERR_FORMAT    Formato incorrecto.
441#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
442#@version 0.9 - Adaptación a OpenGnSys.
443#@author  Antonio J. Doblas Viso. Universidad de Málaga
444#@date    2009-09-24
445#*/ ##
446
447function ogBootMbrGeneric ()
448{
449# Variables locales.
450local DISK
451
452# Si se solicita, mostrar ayuda.
453if [ "$*" == "help" ]; then
454    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
455           "$FUNCNAME 1 "
456    return
457fi
458# Error si no se recibe 1 parámetro.
459[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
460
461DISK="$(ogDiskToDev $1)" || return $?
462ms-sys -z -f $DISK
463ms-sys -s -f $DISK
464}
465
466
467
468
469#/**
470#         ogFixBootSector int_ndisk int_parition
471#@brief   Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
472#@param   int_ndisk      nº de orden del disco
473#@param   int_partition     nº de particion
474#@return 
475#@exception OG_ERR_FORMAT    Formato incorrecto.
476#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
477#@version 0.9 - Adaptación a OpenGnSys.
478#@author  Antonio J. Doblas Viso. Universidad de Málaga
479#@date    2009-09-24
480#*/ ##
481
482function ogFixBootSector ()
483{
484# Variables locales.
485local PARTYPE DISK PART FILE
486
487# Si se solicita, mostrar ayuda.
488if [ "$*" == "help" ]; then
489    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
490           "$FUNCNAME 1 1 "
491    return
492fi
493
494# Error si no se reciben 2 parámetros.
495[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
496
497#TODO, solo si la particion existe
498#TODO, solo si es ntfs o fat
499PARTYPE=$(ogGetPartitionId $1 $2)
500case "$PARTYPE" in
501        1|4|6|7|b|c|e|f|17|700|EF00)
502        ;;
503        *)
504        return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
505        ;;
506esac
507
508ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
509
510#Preparando instruccion
511let DISK=$1-1   
512PART=$2
513FILE=/tmp/temp$$
514cat > $FILE <<EOF
515disk=$DISK
516main_part=$PART
517fix_first_sector=yes
518EOF
519
520timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -a -f $FILE
521rm -f $FILE
522}
523
524
525
526#/**
527#         ogWindowsBootParameters int_ndisk int_parition
528#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
529#@param   int_ndisk      nº de orden del disco
530#@param   int_partition     nº de particion
531#@return 
532#@exception OG_ERR_FORMAT    Formato incorrecto.
533#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
534#@version 0.9 - Integración desde EAC para OpenGnSys.
535#@author  Antonio J. Doblas Viso. Universidad de Málaga
536#@date    2009-09-24
537#@version 1.0.1 - Adapatacion para OpenGnsys.
538#@author  Antonio J. Doblas Viso. Universidad de Málaga
539#@date    2011-05-20
540#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
541#@author  Ramon Gomez, ETSII Universidad de Sevilla
542#@date    2014-01-28
543#@version 1.1.0 - Soporte para Windows 10.
544#@author  Ramon Gomez, ETSII Universidad de Sevilla
545#@date    2016-01-19
546#@version 1.1.1 - Compatibilidad con UEFI (ticket #802 #889)
547#@author  Irina Gomez, ETSII Universidad de Sevilla
548#@date    2019-01-28
549#*/ ##
550
551function ogWindowsBootParameters ()
552{
553# Variables locales.
554local PART DISK BOOTLABEL BCDFILE BOOTDISK BOOTPART FILE WINVER MOUNT
555
556# Si se solicita, mostrar ayuda.
557if [ "$*" == "help" ]; then
558    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
559           "$FUNCNAME 1 1 "
560    return
561fi
562
563# Error si no se reciben 2 parámetros.
564[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
565
566ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
567
568#Preparando variables adaptadas a sintaxis windows.
569let DISK=$1-1
570PART=$2
571FILE=/tmp/temp$$
572if ogIsEfiActive; then
573    read BOOTDISK BOOTPART <<< $(ogGetEsp)
574    ogUnmount $BOOTDISK $BOOTPART || ogRaiseError $OG_ERR_PARTITION "ESP: $BOOTDISK $BOOTPART" || return $?
575
576    let BOOTDISK=$BOOTDISK-1
577    BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
578    BCDFILE="boot_BCD_file=/EFI/$BOOTLABEL/Boot/BCD"
579else
580    BOOTDISK=$DISK
581    BOOTPART=$PART
582    BCDFILE=""
583fi
584
585
586# Obtener versión de Windows.
587WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
588[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?)
589
590# Acciones para Windows XP.
591if [[ "$WINVER" =~ "XP" ]]; then
592    MOUNT=$(ogMount $1 $2)
593    [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?)
594    cat ${MOUNT}/boot.ini | sed s/partition\([0-9]\)/partition\($PART\)/g | sed s/rdisk\([0-9]\)/rdisk\($DISK\)/g > ${MOUNT}/tmp.boot.ini; mv ${MOUNT}/tmp.boot.ini ${MOUNT}/boot.ini
595    return 0
596fi
597
598ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
599
600
601#Preparando instruccion Windows Resume Application
602cat > $FILE <<EOF
603boot_disk=$BOOTDISK
604boot_main_part=$BOOTPART
605$BCDFILE
606disk=$DISK
607main_part=$PART
608boot_entry=Windows Resume Application
609EOF
610timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
611
612
613#Preparando instruccion tipo windows
614cat > $FILE <<EOF
615boot_disk=$BOOTDISK
616boot_main_part=$BOOTPART
617$BCDFILE
618disk=$DISK
619main_part=$PART
620boot_entry=$WINVER
621EOF
622timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
623
624##Preparando instruccion        Ramdisk Options
625cat > $FILE <<EOF
626boot_disk=$BOOTDISK
627boot_main_part=$BOOTPART
628$BCDFILE
629disk=$DISK
630main_part=$PART
631boot_entry=Ramdisk Options
632EOF
633timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
634
635##Preparando instruccion        Recovery Environment
636cat > $FILE <<EOF
637boot_disk=$BOOTDISK
638boot_main_part=$BOOTPART
639$BCDFILE
640disk=$DISK
641main_part=$PART
642boot_entry=Windows Recovery Environment
643EOF
644timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
645
646##Preparando instruccion        Recovery
647cat > $FILE <<EOF
648boot_disk=$BOOTDISK
649boot_main_part=$BOOTPART
650$BCDFILE
651disk=$DISK
652main_part=$PART
653boot_entry=Windows Recovery
654EOF
655timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
656
657#Preparando instruccion Windows Boot Manager
658cat > $FILE <<EOF
659boot_disk=$BOOTDISK
660boot_main_part=$BOOTPART
661$BCDFILE
662disk=$BOOTDISK
663main_part=$BOOTPART
664boot_entry=Windows Boot Manager
665EOF
666timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
667
668#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
669cat > $FILE <<EOF
670boot_disk=$BOOTDISK
671boot_main_part=$BOOTPART
672$BCDFILE
673disk=$BOOTDISK
674main_part=$BOOTPART
675boot_entry=Herramienta de diagnóstico de memoria de Windows
676EOF
677timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
678
679#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
680cat > $FILE <<EOF
681boot_disk=$BOOTDISK
682boot_main_part=$BOOTPART
683$BCDFILE
684disk=$BOOTDISK
685main_part=$BOOTPART
686boot_entry=Herramienta de diagn<f3>stico de memoria de Windows
687EOF
688timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
689
690rm -f $FILE
691}
692
693
694
695#/**
696#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
697#@brief   Registra una partición en windows con un determinado volumen.
698#@param   int_ndisk      nº de orden del disco a registrar
699#@param   int_partition     nº de particion a registrar
700#@param   str_volumen      volumen a resgistar
701#@param   int_ndisk_windows      nº de orden del disco donde esta windows
702#@param   int_partition_windows     nº de particion donde esta windows
703#@return 
704#@exception OG_ERR_FORMAT    Formato incorrecto.
705#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
706#@version 0.9 - Adaptación a OpenGnSys.
707#@author  Antonio J. Doblas Viso. Universidad de Málaga
708#@date    2009-09-24
709#*/ ##
710function ogWindowsRegisterPartition ()
711{
712# Variables locales.
713local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
714
715# Si se solicita, mostrar ayuda.
716if [ "$*" == "help" ]; then
717    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
718           "$FUNCNAME 1 1 c: 1 1"
719    return
720fi
721
722# Error si no se reciben 5 parámetros.
723[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
724
725REGISTREDDISK=$1
726REGISTREDPART=$2
727REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
728DISK=$4
729PART=$5
730FILE=/tmp/temp$$
731
732ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
733ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
734
735ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
736
737VERSION=$(ogGetOsVersion $DISK $PART)
738
739#Systemroot
740
741if ogGetPath $DISK $PART WINDOWS
742then
743        SYSTEMROOT="Windows"
744elif ogGetPath $DISK $PART WINNT
745then
746        SYSTEMROOT="winnt"
747else
748        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
749fi
750
751ogUnmount $DISK $PART
752let DISK=$DISK-1
753let REGISTREDDISK=$REGISTREDDISK-1
754#Preparando instruccion Windows Boot Manager
755cat > $FILE <<EOF
756windows_disk=$DISK
757windows_main_part=$PART
758windows_dir=$SYSTEMROOT
759disk=$REGISTREDDISK
760main_part=$REGISTREDPART
761;ext_part
762part_letter=$REGISTREDVOL
763EOF
764timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -u -f $FILE
765
766}
767
768#/**
769#         ogGrubInstallMbr  int_disk_GRUBCFG  int_partition_GRUBCFG 
770#@brief   Instala el grub el el MBR del primer disco duro (FIRSTSTAGE). El fichero de configuración grub.cfg ubicado según parametros disk y part(SECONDSTAGE). Admite sistemas Windows.
771#@param   int_disk_SecondStage     
772#@param   int_part_SecondStage     
773#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
774#@return 
775#@exception OG_ERR_FORMAT    Formato incorrecto.
776#@version 1.0.2 - Primeras pruebas.
777#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
778#@date    2011-10-29
779#@version 1.0.3 - Soporte para linux de 32 y 64 bits
780#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
781#@date    2012-03-13
782#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
783#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
784#@date    2012-03-13
785#@version 1.1.0 - #791 El FIRSTSTAGE(MBR) siempre será el primer disco duro. EL SECONDSTAGE(grub.cfg) estára en el DISK y PART indicados en los parámetros.
786#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
787#@date    2017-06-19
788#@version 1.1.0 - #827 Entrada para el ogLive si el equipo tiene partición cache.
789#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
790#@date    2018-01-21
791#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
792#@author Irina Gomez, ETSII Universidad de Sevilla
793#@date    2019-01-08
794#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
795#@author  Irina Gomez, ETSII Universidad de Sevilla
796#@date    2019-03-05
797#*/ ##
798
799function ogGrubInstallMbr ()
800{
801
802# Variables locales.
803local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
804local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
805
806# Si se solicita, mostrar ayuda.
807if [ "$*" == "help" ]; then
808    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
809           "$FUNCNAME 1 1 FALSE " \
810           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
811    return
812fi 
813
814# Error si no se reciben 2 parámetros.
815[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
816
817
818DISK=$1; PART=$2;
819CHECKOS=${3:-"FALSE"}
820KERNELPARAM=$4
821BACKUPNAME=".backup.og"
822
823#Error si no es linux.
824#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
825#VERSION=$(ogGetOsVersion $DISK $PART)
826#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
827
828#La primera etapa del grub se fija en el primer disco duro
829FIRSTSTAGE=$(ogDiskToDev 1)
830
831#localizar disco segunda etapa del grub
832SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
833
834# prepara el directorio principal de la segunda etapa
835[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
836
837#Localizar directorio segunda etapa del grub   
838PREFIXSECONDSTAGE="/boot/grubMBR"
839
840# Instalamos grub para EFI en ESP
841if ogIsEfiActive; then
842    read EFIDISK EFIPART <<< $(ogGetEsp)
843    # Comprobamos que exista ESP y el directorio para ubuntu
844    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
845    if [ $? -ne 0 ]; then
846        ogFormat $EFIDISK $EFIPART FAT32
847        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
848    fi
849    EFISUBDIR="grub"
850    # Borramos la configuración anterior
851    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
852    mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
853    EFIOPTGRUB=" --no-nvram --target x86_64-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
854else
855    EFIOPTGRUB=""
856fi
857
858# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
859if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
860then
861    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
862    then
863        # Si no se reconfigura se utiliza el grub.cfg orginal
864        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
865                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
866        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
867        # Reactivamos el grub con el grub.cfg original.
868        grub-install --force ${EFIOPTGRUB} --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#*/ ##
1590
1591function ogBurgInstallMbr ()
1592{
1593 
1594# Variables locales.
1595local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1596
1597# Si se solicita, mostrar ayuda.
1598if [ "$*" == "help" ]; then
1599    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1600           "$FUNCNAME 1 1 FALSE " \
1601           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1602    return
1603fi 
1604
1605# Error si no se reciben 2 parametros.
1606[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1607
1608
1609DISK=$1; PART=$2;
1610CHECKOS=${3:-"FALSE"}
1611KERNELPARAM=$4
1612BACKUPNAME=".backup.og"
1613
1614#Error si no es linux.
1615ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1616
1617
1618#La primera etapa del grub se fija en el primer disco duro
1619FIRSTSTAGE=$(ogDiskToDev 1)
1620
1621#localizar disco segunda etapa del grub
1622SECONDSTAGE=$(ogMount $DISK $PART)
1623
1624# prepara el directorio principal de la segunda etapa (y copia los binarios)
1625[ -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)
1626
1627#Copiamos el tema
1628mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1629cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
1630
1631#Localizar directorio segunda etapa del grub   
1632#PREFIXSECONDSTAGE="/boot/burg/"
1633
1634# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1635if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1636then
1637    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1638    then
1639        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1640        return $?
1641    fi
1642fi
1643
1644# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1645
1646#llamada a updateBootCache para que aloje la primera fase del ogLive
1647updateBootCache
1648
1649#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1650echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1651echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1652
1653
1654#Preparar configuración segunda etapa: crear ubicacion
1655mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1656
1657#Preparar configuración segunda etapa: crear cabecera del fichero
1658#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1659
1660FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1661
1662#/* ## (comentario Dogygen)
1663cat > "$FILECFG" << EOF
1664
1665set theme_name=OpenGnsys
1666set gfxmode=1024x768
1667
1668
1669set locale_dir=(\$root)/boot/burg/locale
1670
1671set default=0
1672set timeout=25
1673set lang=es
1674
1675
1676insmod ext2
1677insmod gettext
1678
1679
1680
1681
1682if [ -s \$prefix/burgenv ]; then
1683  load_env
1684fi
1685
1686
1687
1688if [ \${prev_saved_entry} ]; then
1689  set saved_entry=\${prev_saved_entry}
1690  save_env saved_entry
1691  set prev_saved_entry=
1692  save_env prev_saved_entry
1693  set boot_once=true
1694fi
1695
1696function savedefault {
1697  if [ -z \${boot_once} ]; then
1698    saved_entry=\${chosen}
1699    save_env saved_entry
1700  fi
1701}
1702function select_menu {
1703  if menu_popup -t template_popup theme_menu ; then
1704    free_config template_popup template_subitem menu class screen
1705    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1706    save_env theme_name
1707    menu_refresh
1708  fi
1709}
1710
1711function toggle_fold {
1712  if test -z $theme_fold ; then
1713    set theme_fold=1
1714  else
1715    set theme_fold=
1716  fi
1717  save_env theme_fold
1718  menu_refresh
1719}
1720function select_resolution {
1721  if menu_popup -t template_popup resolution_menu ; then
1722    menu_reload_mode
1723    save_env gfxmode
1724  fi
1725}
1726
1727
1728if test -f \${prefix}/themes/\${theme_name}/theme ; then
1729  insmod coreui
1730  menu_region.text
1731  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1732  load_config \${prefix}/themes/conf.d/10_hotkey   
1733  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1734  insmod vbe
1735  insmod png
1736  insmod jpeg
1737  set gfxfont="Unifont Regular 16"
1738  menu_region.gfx
1739  vmenu resolution_menu
1740  controller.ext
1741fi
1742
1743
1744EOF
1745#*/ ## (comentario Dogygen)
1746
1747#Preparar configuración segunda etapa: crear entrada del sistema operativo
1748grubSyntax "$KERNELPARAM" >> "$FILECFG"
1749
1750#Instalar el burg
1751burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1752}
1753
1754#/**
1755# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1756#@brief ver ogBootLoaderDefaultEntry
1757#@see ogBootLoaderDefaultEntry
1758#*/ ##
1759function ogGrubDefaultEntry ()
1760{
1761    # Si se solicita, mostrar ayuda.
1762    if [ "$*" == "help" ]; then
1763        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1764               "$FUNCNAME 1 6 1 1"
1765        return
1766    fi
1767    ogBootLoaderDefaultEntry $@
1768    return $?
1769}
1770
1771#/**
1772# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1773#@brief ver ogBootLoaderDefaultEntry
1774#@see ogBootLoaderDefaultEntry
1775#*/ ##
1776function ogBurgDefaultEntry ()
1777{
1778    # Si se solicita, mostrar ayuda.
1779    if [ "$*" == "help" ]; then
1780        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1781               "$FUNCNAME 1 6 1 1"
1782        return
1783    fi
1784    ogBootLoaderDefaultEntry $@
1785    return $?
1786}
1787
1788#/**
1789# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1790#@brief   Configura la entrada por defecto de Burg
1791#@param   int_disk_SecondStage     
1792#@param   int_part_SecondStage     
1793#@param   int_disk_default_entry
1794#@param   int_part_default_entry
1795#@return 
1796#@exception OG_ERR_FORMAT    Formato incorrecto.
1797#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1798#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1799#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1800#@version 1.1.0 - Define la entrada por defecto del Burg
1801#@author  Irina Gomez, ETSII Universidad de Sevilla
1802#@date    2017-08-09
1803#@version 1.1 Se generaliza la función para grub y burg
1804#@author  Irina Gomez, ETSII Universidad de Sevilla
1805#@date    2018-01-04
1806#*/ ##
1807function ogBootLoaderDefaultEntry ()
1808{
1809
1810# Variables locales.
1811local PART CFGFILE DEFAULTENTRY MSG
1812
1813# Si se solicita, mostrar ayuda.
1814if [ "$*" == "help" ]; then
1815    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
1816    return
1817fi 
1818
1819# Nombre de la función que llama a esta.
1820FUNC="${FUNCNAME[@]:1}"
1821FUNC="${FUNC%%\ *}"
1822
1823# Error si no se reciben 3 parametros.
1824[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1825
1826# Error si no puede montar sistema de archivos.
1827DIRMOUNT=$(ogMount $1 $2) || return $?
1828
1829# Comprobamos que exista fichero de configuración
1830# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1831case "$FUNC" in
1832    ogGrubDefaultEntry)
1833        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1834        ;;
1835    ogBurgDefaultEntry)
1836        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1837        ;;
1838    *)
1839        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1840        return $?
1841        ;;
1842esac
1843
1844# Error si no existe archivo de configuración
1845[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1846
1847# Dispositivo
1848DEVICE=$(ogDiskToDev $3 $4)
1849
1850# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1851DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1852
1853# Si no hay entradas para borrar me salgo con aviso
1854[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
1855
1856# Número de la de linea por defecto en el menú de usuario
1857MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1858# Las líneas empiezan a contar desde cero
1859let MENUENTRY=$MENUENTRY-1
1860sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1861MSG="MSG_HELP_$FUNC"
1862echo "${!MSG%%\.}: $@"
1863}
1864
1865#/**
1866# ogGrubOgliveDefaultEntry num_disk num_part
1867#@brief ver ogBootLoaderOgliveDefaultEntry
1868#@see ogBootLoaderOgliveDefaultEntry
1869#*/ ##
1870function ogGrubOgliveDefaultEntry ()
1871{
1872    # Si se solicita, mostrar ayuda.
1873    if [ "$*" == "help" ]; then
1874        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1875               "$FUNCNAME 1 6"
1876        return
1877    fi
1878    ogBootLoaderOgliveDefaultEntry $@
1879    return $?
1880}
1881
1882#/**
1883# ogBurgOgliveDefaultEntry num_disk num_part
1884#@brief ver ogBootLoaderOgliveDefaultEntry
1885#@see ogBootLoaderOgliveDefaultEntry
1886#*/ ##
1887function ogBurgOgliveDefaultEntry ()
1888{
1889    # Si se solicita, mostrar ayuda.
1890    if [ "$*" == "help" ]; then
1891        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1892               "$FUNCNAME 1 6"
1893        return
1894    fi
1895    ogBootLoaderOgliveDefaultEntry $@
1896    return $?
1897}
1898
1899#/**
1900# ogBootLoaderOgliveDefaultEntry
1901#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1902#@param   int_disk_SecondStage     
1903#@param   int_part_SecondStage     
1904#@return 
1905#@exception OG_ERR_FORMAT    Formato incorrecto.
1906#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1907#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1908#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1909#@version 1.1.0 - Primeras pruebas con Burg
1910#@author  Irina Gomez, ETSII Universidad de Sevilla
1911#@date    2017-08-09
1912#@version 1.1 Se generaliza la función para grub y burg
1913#@author  Irina Gomez, ETSII Universidad de Sevilla
1914#@date    2018-01-04
1915#*/ ##
1916function  ogBootLoaderOgliveDefaultEntry ()
1917{
1918
1919# Variables locales.
1920local FUNC PART CFGFILE NUMENTRY MSG
1921
1922# Si se solicita, mostrar ayuda.
1923if [ "$*" == "help" ]; then
1924    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
1925    return
1926fi 
1927
1928# Nombre de la función que llama a esta.
1929FUNC="${FUNCNAME[@]:1}"
1930FUNC="${FUNC%%\ *}"
1931
1932# Error si no se reciben 2 parametros.
1933[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1934
1935# Error si no puede montar sistema de archivos.
1936PART=$(ogMount $1 $2) || return $?
1937# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1938case "$FUNC" in
1939    ogGrubOgliveDefaultEntry)
1940        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1941        ;;
1942    ogBurgOgliveDefaultEntry)
1943        CFGFILE="$PART/boot/burg/burg.cfg"
1944        ;;
1945    *)
1946        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1947        return $?
1948        ;;
1949esac
1950
1951# Comprobamos que exista fichero de configuración
1952[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1953
1954# Detectamos cual es la entrada de ogLive
1955NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
1956
1957# Si no existe entrada de ogLive nos salimos
1958[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
1959
1960let NUMENTRY=$NUMENTRY-1
1961sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
1962
1963MSG="MSG_HELP_$FUNC"
1964echo "${!MSG%%\.}: $@"
1965}
1966
1967
1968#/**
1969# ogGrubSetTheme num_disk num_part str_theme
1970#@brief ver ogBootLoaderSetTheme
1971#@see ogBootLoaderSetTheme
1972#*/ ##
1973function ogGrubSetTheme ()
1974{
1975    # Si se solicita, mostrar ayuda.
1976    if [ "$*" == "help" ]; then
1977        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1978               "$FUNCNAME 1 4 ThemeBasic"\
1979               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1980        return
1981    fi
1982    ogBootLoaderSetTheme $@
1983    return $?
1984}
1985
1986#/**
1987# ogBurgSetTheme num_disk num_part str_theme
1988#@brief ver ogBootLoaderSetTheme
1989#@see ogBootLoaderSetTheme
1990#*/ ##
1991function ogBurgSetTheme  ()
1992{
1993    # Si se solicita, mostrar ayuda.
1994    if [ "$*" == "help" ]; then
1995        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1996               "$FUNCNAME 1 4 ThemeBasic" \
1997               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1998        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
1999               
2000        return
2001    fi
2002    ogBootLoaderSetTheme $@
2003    return $?
2004}
2005
2006
2007#/**
2008# ogRefindSetTheme int_ndiskESP int_partitionESP str_theme
2009#@brief ver ogBootLoaderSetTheme
2010#@see ogBootLoaderSetTheme
2011#*/ ##
2012function ogRefindSetTheme () {
2013    local PART DIRTHEME CFGFILE
2014    # Si se solicita, mostrar ayuda.
2015    if [ "$*" == "help" ]; then
2016        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskESP int_partitionESP str_themeName" \
2017               "$FUNCNAME 1 1 ThemeBasic"
2018        echo -e "\nThemes in $OGLIB/refind:\n$(ls $OGLIB/refind/themes/)"
2019
2020        return
2021    fi
2022
2023    PART=$(ogMount $1 $2) || return $?
2024    DIRTHEME="$PART/EFI/refind/themes"
2025    CFGFILE="$PART/EFI/refind/refind.conf"
2026
2027    # Para utilizar ogBootLoaderSetTheme es necesario la entrada set theme_name
2028    if [ -f $CFGFILE ]; then
2029        sed -i '/showtools/i\set theme_name=none' $CFGFILE
2030    else
2031        ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2032    fi
2033    # Creamos el directorio para los temas
2034    [ -d $DIRTHEME ] || mkdir $DIRTHEME
2035
2036    ogBootLoaderSetTheme $@
2037    return $?
2038}
2039
2040
2041#/**
2042# ogBootLoaderSetTheme
2043#@brief   asigna un tema al BURG
2044#@param   int_disk_SecondStage     
2045#@param   int_part_SecondStage 
2046#@param   str_theme_name   
2047#@return 
2048#@exception OG_ERR_FORMAT    Formato incorrecto.
2049#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2050#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg refind.conf.
2051#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2052#@exception OG_ERR_NOTFOUND  Fichero de configuración del tema no encontrado: theme.conf (sólo refind).
2053#@note    El tema debe situarse en OGLIB/BOOTLOADER/themes
2054#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2055#@author  Antonio J. Doblas Viso. Universidad de Malaga
2056#@date    2018-01-24
2057#@version 1.1.1 - Soporta rEFInd (ticket #802 #888).
2058#@author  Irina Gomez. Universidad de Sevilla
2059#@date    2019-03-22
2060#*/ ##
2061function  ogBootLoaderSetTheme ()
2062{
2063
2064# Variables locales.
2065local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG NEWTHEMECFG
2066
2067# Si se solicita, mostrar ayuda.
2068if [ "$*" == "help" ]; then
2069    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme"
2070    return   
2071fi
2072 
2073
2074NEWTHEME="$3"
2075
2076# Nombre de la función que llama a esta.
2077FUNC="${FUNCNAME[@]:1}"
2078FUNC="${FUNC%%\ *}"
2079
2080
2081
2082# Error si no se reciben 3 parametros.
2083[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
2084
2085# Error si no puede montar sistema de archivos.
2086PART=$(ogMount $1 $2) || return $?
2087# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme.
2088case "$FUNC" in
2089    ogGrubSetTheme)
2090        BOOTLOADER="grug"
2091        BOOTLOADERDIR="boot/grubMBR"
2092        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2093        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
2094        return $?               
2095        ;;
2096    ogBurgSetTheme)
2097        BOOTLOADER="burg"
2098        BOOTLOADERDIR="boot/burg"
2099        CFGFILE="$PART/boot/burg/burg.cfg"       
2100        ;;
2101    ogRefindSetTheme)
2102        BOOTLOADER="refind"
2103        BOOTLOADERDIR="EFI/refind"
2104        CFGFILE="$PART/EFI/refind/refind.conf"
2105        ;;
2106    *)
2107        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
2108        return $?
2109        ;;
2110esac
2111
2112# Comprobamos que exista fichero de configuración
2113[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2114
2115# Detectamos cual es el tema asignado
2116THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
2117# Si no existe entrada de theme_name  nos salimos
2118[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
2119
2120#Actualizamos el tema del servidor a la particion
2121if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
2122        # Para refind es necesario que exista theme.conf en el directorio del tema.
2123        if [ "$BOOTLOADER" == "refind" ]; then
2124            NEWTHEMECFG="$OGLIB/$BOOTLOADER/themes/$NEWTHEME/theme.conf"
2125            [ -f $NEWTHEMECFG ] || ogRaiserError $OG_ERR_NOTFOUND "theme.conf" || return $?
2126            grep -v "^#" $NEWTHEMECFG >> $CFGFILE
2127            # eliminamos "set theme" es de grub y no de refind
2128            sed -i '/theme_name/d' $CFGFILE
2129        fi
2130        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/$BOOTLOADERDIR/themes/
2131fi
2132
2133#Verificamos que el tema esta en la particion
2134if ! [ -d $PART/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
2135                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/$BOOTLOADERDIR/themes/" || return $?
2136fi
2137
2138#Cambiamos la entrada el fichero de configuración.
2139sed --regexp-extended -i  s/"set theme_name=$THEME"/"set theme_name=$NEWTHEME"/g $CFGFILE
2140
2141
2142}
2143
2144#/**
2145# ogGrubSetAdminKeys num_disk num_part str_theme
2146#@brief ver ogBootLoaderSetTheme
2147#@see ogBootLoaderSetTheme
2148#*/ ##
2149function ogGrubSetAdminKeys ()
2150{
2151    # Si se solicita, mostrar ayuda.
2152    if [ "$*" == "help" ]; then
2153        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2154               "$FUNCNAME 1 4 FALSE "\
2155               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2156        return
2157    fi
2158    ogBootLoaderSetAdminKeys $@
2159    return $?
2160}
2161
2162#/**
2163# ogBurgSetAdminKeys num_disk num_part str_bolean
2164#@brief ver ogBootLoaderSetAdminKeys
2165#@see ogBootLoaderSetAdminKeys
2166#*/ ##
2167function ogBurgSetAdminKeys  ()
2168{
2169    # Si se solicita, mostrar ayuda.
2170    if [ "$*" == "help" ]; then
2171        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2172               "$FUNCNAME 1 4 TRUE" \
2173               "$FUNCNAME \$(ogFindCache) FALSE"               
2174        return
2175    fi
2176    ogBootLoaderSetAdminKeys $@
2177    return $?
2178}
2179
2180
2181
2182#/**
2183# ogBootLoaderSetAdminKeys
2184#@brief   Activa/Desactica las teclas de administracion
2185#@param   int_disk_SecondStage     
2186#@param   int_part_SecondStage 
2187#@param   Boolean TRUE/FALSE   
2188#@return 
2189#@exception OG_ERR_FORMAT    Formato incorrecto.
2190#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2191#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2192#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2193#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2194#@author  Antonio J. Doblas Viso. Universidad de Malaga
2195#@date    2018-01-24
2196#*/ ##
2197function  ogBootLoaderSetAdminKeys ()
2198{
2199
2200# Variables locales.
2201local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2202
2203# Si se solicita, mostrar ayuda.
2204if [ "$*" == "help" ]; then
2205    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2206    return   
2207fi
2208 
2209
2210# Nombre de la función que llama a esta.
2211FUNC="${FUNCNAME[@]:1}"
2212FUNC="${FUNC%%\ *}"
2213
2214
2215# Error si no se reciben 2 parametros.
2216[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2217
2218# Error si no puede montar sistema de archivos.
2219PART=$(ogMount $1 $2) || return $?
2220# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2221case "$FUNC" in
2222    ogGrubSetAdminKeys)
2223        BOOTLOADER="grug"
2224        BOOTLOADERDIR="grubMBR"
2225        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2226        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2227        return $?       
2228        ;;
2229    ogBurgSetAdminKeys)
2230        BOOTLOADER="burg"
2231        BOOTLOADERDIR="burg"
2232        CFGFILE="$PART/boot/burg/burg.cfg"       
2233        ;;
2234    *)
2235        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2236        return $?
2237        ;;
2238esac
2239
2240
2241# Comprobamos que exista fichero de configuración
2242[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2243
2244
2245case "$3" in
2246        true|TRUE)
2247                [ -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
2248        ;;
2249        false|FALSE)
2250                [ -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
2251        ;;     
2252        *)
2253           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2254        return $?
2255    ;; 
2256esac
2257}
2258
2259
2260
2261#/**
2262# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
2263#@brief ver ogBootLoaderSetTimeOut
2264#@see ogBootLoaderSetTimeOut
2265#*/ ##
2266function ogGrubSetTimeOut ()
2267{
2268    # Si se solicita, mostrar ayuda.
2269    if [ "$*" == "help" ]; then
2270        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2271               "$FUNCNAME 1 4 50 "\
2272               "$FUNCNAME \$(ogFindCache) 50"
2273        return
2274    fi
2275    ogBootLoaderSetTimeOut $@
2276    return $?
2277}
2278
2279#/**
2280# ogBurgSetTimeOut num_disk num_part str_bolean
2281#@brief ver ogBootLoaderSetTimeOut
2282#@see ogBootLoaderSetTimeOut
2283#*/ ##
2284function ogBurgSetTimeOut ()
2285{
2286    # Si se solicita, mostrar ayuda.
2287    if [ "$*" == "help" ]; then
2288        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2289               "$FUNCNAME 1 4 50" \
2290               "$FUNCNAME \$(ogFindCache) 50"               
2291        return
2292    fi
2293    ogBootLoaderSetTimeOut $@
2294    return $?
2295}
2296
2297
2298
2299#/**
2300# ogBootLoaderSetTimeOut
2301#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2302#@param   int_disk_SecondStage     
2303#@param   int_part_SecondStage 
2304#@param   int_timeout_seconds   
2305#@return 
2306#@exception OG_ERR_FORMAT    Formato incorrecto.
2307#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2308#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2309#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2310#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2311#@author  Antonio J. Doblas Viso. Universidad de Malaga
2312#@date    2018-01-24
2313#*/ ##
2314function  ogBootLoaderSetTimeOut ()
2315{
2316
2317# Variables locales.
2318local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2319
2320# Si se solicita, mostrar ayuda.
2321if [ "$*" == "help" ]; then
2322    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut"
2323    return   
2324fi
2325 
2326ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2327
2328# Nombre de la función que llama a esta.
2329FUNC="${FUNCNAME[@]:1}"
2330FUNC="${FUNC%%\ *}"
2331
2332# Error si no se reciben 3 parametros.
2333[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2334
2335# Error si no puede montar sistema de archivos.
2336PART=$(ogMount $1 $2) || return $?
2337# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut.
2338case "$FUNC" in
2339    ogGrubSetTimeOut)
2340        BOOTLOADER="grug"
2341        BOOTLOADERDIR="grubMBR"
2342        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2343        ;;
2344    ogBurgSetTimeOut)
2345        BOOTLOADER="burg"
2346        BOOTLOADERDIR="burg"
2347        CFGFILE="$PART/boot/burg/burg.cfg"       
2348        ;;
2349    *)
2350        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut"
2351        return $?
2352        ;;
2353esac
2354
2355# Comprobamos que exista fichero de configuración
2356[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2357
2358# Asignamos el timeOut.
2359sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2360}
2361
2362
2363#/**
2364# ogGrubSetResolution num_disk num_part int_resolution
2365#@brief ver ogBootLoaderSetResolution
2366#@see ogBootLoaderSetResolution
2367#*/ ##
2368function ogGrubSetResolution ()
2369{
2370    # Si se solicita, mostrar ayuda.
2371    if [ "$*" == "help" ]; then
2372        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2373             "$FUNCNAME 1 4 1024x768" \
2374             "$FUNCNAME \$(ogFindCache) 1024x768" \
2375             "$FUNCNAME 1 4" 
2376        return
2377    fi
2378    ogBootLoaderSetResolution $@
2379    return $?
2380}
2381
2382#/**
2383# ogBurgSetResolution num_disk num_part str_bolean
2384#@brief ver ogBootLoaderSetResolution
2385#@see ogBootLoaderSetResolution
2386#*/ ##
2387function ogBurgSetResolution ()
2388 {
2389    # Si se solicita, mostrar ayuda.
2390    if [ "$*" == "help" ]; then
2391        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2392               "$FUNCNAME 1 4 1024x768" \
2393               "$FUNCNAME \$(ogFindCache) 1024x768" \
2394               "$FUNCNAME 1 4"               
2395        return
2396    fi
2397    ogBootLoaderSetResolution $@
2398    return $?
2399}
2400
2401
2402
2403#/**
2404# ogBootLoaderSetResolution
2405#@brief   Define la resolucion que usuara el thema del gestor de arranque
2406#@param   int_disk_SecondStage     
2407#@param   int_part_SecondStage 
2408#@param   str_resolution (Opcional)   
2409#@return 
2410#@exception OG_ERR_FORMAT    Formato incorrecto.
2411#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2412#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2413#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2414#@author  Antonio J. Doblas Viso. Universidad de Malaga
2415#@date    2018-01-24
2416#*/ ##
2417function  ogBootLoaderSetResolution ()
2418{
2419
2420# Variables locales.
2421local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2422
2423# Si se solicita, mostrar ayuda.
2424if [ "$*" == "help" ]; then
2425    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution"
2426    return   
2427fi
2428
2429
2430# Nombre de la función que llama a esta.
2431FUNC="${FUNCNAME[@]:1}"
2432FUNC="${FUNC%%\ *}"
2433
2434
2435# Error si no se reciben 2 parametros.
2436[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2437
2438# Error si no puede montar sistema de archivos.
2439PART=$(ogMount $1 $2) || return $?
2440# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution.
2441case "$FUNC" in
2442    ogGrubSetResolution)
2443        BOOTLOADER="grug"
2444        BOOTLOADERDIR="grubMBR"
2445        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2446        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2447        return $?     
2448        ;;
2449    ogBurgSetResolution)
2450        BOOTLOADER="burg"
2451        BOOTLOADERDIR="burg"
2452        CFGFILE="$PART/boot/burg/burg.cfg"       
2453        ;;
2454    *)
2455        ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution"
2456        return $?
2457        ;;
2458esac
2459
2460DEFAULTRESOLUTION=1024x768
2461
2462# Comprobamos que exista fichero de configuración
2463[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2464
2465#controlar variable a consierar vga (default template) o video (menu)
2466#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2467if [ $# -eq 2 ] ; then 
2468        if [ -n $video ]; then
2469                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2470        fi
2471        if [ -n $vga ] ; then
2472        case "$vga" in
2473                788|789|814)
2474                        NEWRESOLUTION=800x600
2475                        ;;
2476                791|792|824)
2477                        NEWRESOLUTION=1024x768
2478                        ;;
2479                355)
2480                        NEWRESOLUTION=1152x864
2481                        ;;
2482                794|795|829)
2483                        NEWRESOLUTION=1280x1024
2484                        ;;
2485        esac
2486        fi
2487fi
2488
2489if [ $# -eq 3 ] ; then
2490        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2491        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"
2492fi
2493
2494# Si no existe NEWRESOLUCION  asignamos la defaulT
2495[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2496
2497#Cambiamos la entrada el fichero de configuración.
2498sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2499}
2500
2501#         ogRefindInstall bool_autoconfig
2502#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2503#@param   bolean_Check__auto_config   true | false[default]
2504#@return
2505#@exception OG_ERR_FORMAT    Formato incorrecto.
2506#@exception OG_ERR_NOTFOUND  No se encuentra la partición ESP.
2507#@exception OG_ERR_NOTFOUND  No se encuentra shimx64.efi.signed.
2508#@exception OG_ERR_NOTFOUND  No se encuentra refind-install o refind en OGLIB
2509#@exception OG_ERR_PARTITION No se puede montar la partición ESP.
2510#@note    Refind debe estar instalado en el ogLive o compartido en OGLIB
2511#@version 1.1.0 - Primeras pruebas.
2512#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2513#@date    2017-06-26
2514#@version 1.1.1 - Usa refind-install. Obtiene partición con ogGetEsp. Configura Part-X-Y y ogLive.
2515#@author  Irina Gomez. Universidad de Sevilla.
2516#@date    2019-03-22
2517#*/ ##
2518function ogRefindInstall () {
2519# Variables locales.
2520local CONFIG EFIDISK EFIPART EFIDEVICE EFIMNT EFIDIR SHIM DIRREFIND CFGFILE DIR OGLIVE CMDLINE
2521
2522# Si se solicita, mostrar ayuda.
2523if [ "$*" == "help" ]; then
2524    ogHelp "$FUNCNAME" "$FUNCNAME boolean_autoconfig " \
2525           "$FUNCNAME 1 TRUE"
2526    return
2527fi
2528
2529# Recogemos parametros
2530CONFIG=${1:-"FALSE"}
2531
2532read -e EFIDISK EFIPART  <<< $(ogGetEsp)
2533EFIDEVICE=$(ogDiskToDev $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_NOTFOUND "ESP" || return $?
2534EFIMNT=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR mount ESP" || return $?
2535EFIDIR="$EFIMNT/EFI"
2536[ -d $EFIDIR ] || mkdir $EFIDIR
2537
2538# Instalamos rEFInd. Con refind-install o copiandolo del OGLIB
2539if which refind-install &>/dev/null; then
2540    # Comprobamos que exista shimx64
2541    SHIM=$(ogGetPath /usr/lib/shim/shimx64.efi.signed)
2542    [ "$SHIM" == "" ] && return $(ogRaiseError $OG_ERR_NOTFOUND "shimx64.efi.signed")
2543
2544    refind-install --yes --alldrivers --usedefault $EFIDEVICE  --shim $SHIM
2545
2546    # Cambiamos el nombre del directorio
2547    [ -d $EFIDIR/refind ] && rm -rf $EFIDIR/refind
2548    mv $EFIDIR/BOOT  $EFIDIR/refind
2549
2550    # Desmontamos directorio temporal
2551    umount /tmp/refind_install
2552else
2553    DIRREFIND=$OGLIB/refind
2554    [ -d $DIRREFIND ] || ogRaiseError $OG_ERR_NOTFOUND "refind-install or $DIRREFIND" || return $?
2555    cp -r $DIRREFIND $EFIDIR
2556fi
2557
2558# Configuramos rEFInd si es necesario
2559if [ "$CONFIG" == "FALSE" ]; then
2560    # Renombramos la configuración por defecto
2561    mv  ${EFIDIR}/refind/refind.conf ${EFIDIR}/refind/refind.conf.auto
2562
2563    # Creamos nueva configuración
2564    CFGFILE="${EFIDIR}/refind/refind.conf"
2565    echo "timeout 20" > $CFGFILE
2566    echo "showtools reboot, shutdown" >> $CFGFILE
2567    echo -e "scanfor manual\n" >> $CFGFILE
2568    if [ -a ${EFIDIR}/Microsoft ]; then
2569        echo "menuentry \"Windows\" {" >> $CFGFILE
2570        echo "    loader /EFI/Microsoft/Boot/bootmgfw.efi" >> $CFGFILE
2571        echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2572        echo "}" >> $CFGFILE
2573    fi
2574    if [ -a ${EFIDIR}/ubuntu ]; then
2575        echo "menuentry \"Ubuntu\" {" >> $CFGFILE
2576        echo "    loader /EFI/ubuntu/grubx64.efi" >> $CFGFILE
2577        echo "    icon /EFI/refind/icons/os_ubuntu.png" >> $CFGFILE
2578        echo "}" >> $CFGFILE
2579    fi
2580    for DIR in $(ls -d /mnt/sda1/EFI/Part-*-* 2>/dev/null); do
2581        echo "menuentry \"${DIR##*/}\" {" >> $CFGFILE
2582        echo "    loader /EFI/${DIR##*/}/Boot/ogloader.efi" >> $CFGFILE
2583        [ -f $DIR/Boot/bootmgfw.efi ] && echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2584        [ -f $DIR/grubx64.efi ] && echo "    icon /EFI/refind/icons/os_linux.png" >> $CFGFILE
2585        echo "}" >> $CFGFILE
2586    done
2587    ogMountCache &>/dev/null
2588    OGLIVE=$(find $OGCAC -name ogvmlinuz|head -1)
2589    if [ "$OGLIVE" != "" ]; then
2590        read -e CACDISK CACPART <<< $(ogFindCache)
2591        # Obtenemos parametros del kernel y sustituimos root
2592        CMDLINE="$(cat /proc/cmdline)"
2593        CMDLINE="root=$(ogDiskToDev $CACDISK $CACPART) ${CMDLINE#*ogvmlinuz}"
2594        echo "menuentry \"OpenGnsys Client\" {" >> $CFGFILE
2595        echo "    volume CACHE" >> $CFGFILE
2596        echo "    ostype Linux" >> $CFGFILE
2597        echo "    loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE
2598        echo "    initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE
2599        echo "    options \"$CMDLINE\"" >> $CFGFILE
2600        echo "    icon /EFI/refind/icons/os_unknown.png" >> $CFGFILE
2601        echo "}" >> $CFGFILE
2602
2603        # Ponemos ogLive como la entrada por defecto
2604        sed -i '/showtools/i\default_selection "OpenGnsys Client"' $CFGFILE
2605    fi
2606fi
2607}
Note: See TracBrowser for help on using the repository browser.