source: client/engine/Boot.lib @ 39b84ff

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

#802 UEFI compatibility: allows postconfigure and log in to Ubuntu.

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