source: client/engine/Boot.lib @ 20e5aa9e

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

#802 #889 configureOs can relocale Windows in different partition. ogWindowsBootParameters: include the bootpartition to configure BCD

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