source: client/engine/Boot.lib @ 7dc06be9

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

#802 #890 Postconfiguración de linux (ubuntu) compatible con UEFI. ogGrubInstallMbr y ogGrubInstallPartition: incluye opciones UEFI. ogUuidChange: genera UUID con un comando existente en el ogLive.

  • Property mode set to 100755
File size: 82.3 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#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
736#@author Irina Gomez, ETSII Universidad de Sevilla
737#@date    2019-01-08
738#*/ ##
739
740function ogGrubInstallMbr ()
741{
742
743# Variables locales.
744local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
745local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
746
747# Si se solicita, mostrar ayuda.
748if [ "$*" == "help" ]; then
749    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
750           "$FUNCNAME 1 1 FALSE " \
751           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
752    return
753fi 
754
755# Error si no se reciben 2 parámetros.
756[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
757
758
759DISK=$1; PART=$2;
760CHECKOS=${3:-"FALSE"}
761KERNELPARAM=$4
762BACKUPNAME=".backup.og"
763
764#Error si no es linux.
765#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
766#VERSION=$(ogGetOsVersion $DISK $PART)
767#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
768
769#La primera etapa del grub se fija en el primer disco duro
770FIRSTSTAGE=$(ogDiskToDev 1)
771
772#localizar disco segunda etapa del grub
773SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
774
775# prepara el directorio principal de la segunda etapa
776[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
777
778#Localizar directorio segunda etapa del grub   
779PREFIXSECONDSTAGE="/boot/grubMBR"
780
781# Instalamos grub para EFI en ESP
782if ogIsEfiActive; then
783    read EFIDISK EFIPART <<< $(ogGetEsp)
784    # Comprobamos que exista ESP y el directorio para ubuntu
785    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
786    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
787    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
788    EFIOPTGRUB=" --target x86_64-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
789else
790    EFIOPTGRUB=""
791fi
792
793# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
794if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
795then
796    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
797    then
798        # Si no se reconfigura se utiliza el grub.cfg orginal
799        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
800                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
801        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
802        # Reactivamos el grub con el grub.cfg original.
803        grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE} $FIRSTSTAGE
804        # Movemos el grubx64.efi
805        if ogIsEfiActive; then
806            mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
807            rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
808        fi
809        return $?
810    fi
811fi
812
813# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
814
815#llamada a updateBootCache para que aloje la primera fase del ogLive
816updateBootCache
817
818#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
819echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
820echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
821
822#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
823[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
824
825#Preparar configuración segunda etapa: crear ubicacion
826mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
827#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
828sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
829/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
830#Preparar configuración segunda etapa: crear entrada del sistema operativo
831grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
832
833#Instalar el grub
834grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
835
836# Movemos el grubx64.efi
837if ogIsEfiActive; then
838    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
839    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
840fi
841}
842
843
844#/**
845#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
846#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
847#@param   int_disk_SecondStage     
848#@param   int_part_SecondStage     
849#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
850#@param   str "kernel param "   
851#@return 
852#@exception OG_ERR_FORMAT    Formato incorrecto.
853#@version 1.0.2 - Primeras pruebas.
854#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
855#@date    2011-10-29
856#@version 1.0.3 - Soporte para linux de 32 y 64 bits
857#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
858#@date    2012-03-13
859#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
860#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
861#@date    2012-03-13
862#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
863#@author Irina Gomez, ETSII Universidad de Sevilla
864#@date    2019-01-08
865#*/ ##
866
867function ogGrubInstallPartition ()
868{
869
870# Variables locales.
871local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
872local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
873
874# Si se solicita, mostrar ayuda.
875if [ "$*" == "help" ]; then
876    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
877           "$FUNCNAME 1 1 FALSE " \
878           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
879    return
880fi 
881
882# Error si no se reciben 2 parámetros.
883[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
884
885DISK=$1; PART=$2;
886CHECKOS=${3:-"FALSE"}
887KERNELPARAM=$4
888BACKUPNAME=".backup.og"
889
890#error si no es linux.
891VERSION=$(ogGetOsVersion $DISK $PART)
892echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
893
894#Localizar primera etapa del grub
895FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
896
897#localizar disco segunda etapa del grub
898SECONDSTAGE=$(ogMount $DISK $PART)
899
900#Localizar directorio segunda etapa del grub   
901PREFIXSECONDSTAGE="/boot/grubPARTITION"
902
903# Si es EFI instalamos el grub en la ESP
904if ogIsEfiActive; then
905    read EFIDISK EFIPART <<< $(ogGetEsp)
906    # Comprobamos que exista ESP y el directorio para ubuntu
907    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
908    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
909    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
910    EFIOPTGRUB=" --target x86_64-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
911else
912    EFIOPTGRUB=""
913fi
914
915# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
916if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
917then
918    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
919    then
920        # Si no se reconfigura se utiliza el grub.cfg orginal
921        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
922                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
923        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
924        # Reactivamos el grub con el grub.cfg original.
925        grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE} $FIRSTSTAGE
926        # Movemos el grubx64.efi
927        if ogIsEfiActive; then
928            mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
929            rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
930        fi
931        return $?
932    fi
933fi
934
935# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
936#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
937echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
938echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
939
940#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
941[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
942
943#Preparar configuración segunda etapa: crear ubicacion
944mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
945#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
946sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
947/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
948#Preparar configuración segunda etapa: crear entrada del sistema operativo
949grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
950
951#Instalar el grub
952grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
953
954# Movemos el grubx64.efi
955if ogIsEfiActive; then
956    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/ubuntu/grubx64.efi ${EFISECONDSTAGE}/EFI/$EFISUBDIR
957    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
958fi
959}
960
961
962#/**
963#         ogConfigureFstab int_ndisk int_nfilesys
964#@brief   Configura el fstab según particiones existentes
965#@param   int_ndisk      nº de orden del disco
966#@param   int_nfilesys   nº de orden del sistema de archivos
967#@return  (nada)
968#@exception OG_ERR_FORMAT    Formato incorrecto.
969#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
970#@warning Puede haber un error si hay más de 1 partición swap.
971#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
972#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
973#@date    2013-03-21
974#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
975#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
976#@date    2016-11-03
977#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
978#@author  Irina Gómez, ETSII Universidad de Sevilla
979#@date    2018-12-13
980#*/ ##
981function ogConfigureFstab ()
982{
983# Variables locales.
984local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
985local EFIDISK EFIPART EFIDEV EFIOPT
986
987# Si se solicita, mostrar ayuda.
988if [ "$*" == "help" ]; then
989    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
990           "$FUNCNAME 1 1"
991    return
992fi
993# Error si no se reciben 2 parámetros.
994[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
995# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
996FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
997[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
998
999# Hacer copia de seguridad del fichero fstab original.
1000cp -a ${FSTAB} ${FSTAB}.backup
1001# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
1002DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
1003PARTROOT=$(ogDiskToDev $1 $2)
1004# Configuración de swap (solo 1ª partición detectada).
1005PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
1006if [ -n "$PARTSWAP" ]
1007then
1008    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
1009    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
1010    if [ -n "$DEFSWAP" ]
1011    then
1012        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
1013        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1014    else
1015        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
1016        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1017        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
1018    fi 
1019else
1020    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
1021    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
1022fi
1023# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
1024if [ ogIsEfiActive ]; then
1025    read EFIDISK EFIPART <<< $(ogGetEsp)
1026    EFIDEV=$(ogDiskToDev $EFIDISK $EFIPART)
1027
1028    # Opciones de la partición ESP: si no existe ponemos un valor por defecto
1029    EFIOPT=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
1030    [ "$EFIOPT" == "" ] && EFIOPT='vfat\tumask=0077\t0\t1'
1031
1032    sed -i /"boot\/efi"/d  ${FSTAB}
1033    echo -e "$EFIDEV\t/boot/efi\t$EFIOPT" >> ${FSTAB}
1034fi
1035}
1036
1037#/**
1038#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
1039#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
1040#@param   int_ndisk      nº de orden del disco
1041#@param   int_nfilesys   nº de orden del sistema de archivos
1042#@param   str_name       nombre asignado (opcional)
1043#@return  (nada)
1044#@exception OG_ERR_FORMAT    Formato incorrecto.
1045#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1046#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1047#@note    Si no se indica nombre, se asigna un valor por defecto.
1048#@version 1.0.5 - Primera versión para OpenGnSys.
1049#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1050#@date    2013-03-21
1051#*/ ##
1052function ogSetLinuxName ()
1053{
1054# Variables locales.
1055local MNTDIR ETC NAME
1056
1057# Si se solicita, mostrar ayuda.
1058if [ "$*" == "help" ]; then
1059    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
1060           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
1061    return
1062fi
1063# Error si no se reciben 2 o 3 parámetros.
1064case $# in
1065    2)   # Asignar nombre automático (por defecto, "pc").
1066         NAME="$(ogGetHostname)"
1067         NAME=${NAME:-"pc"} ;;
1068    3)   # Asignar nombre del 3er parámetro.
1069         NAME="$3" ;;
1070    *)   # Formato de ejecución incorrecto.
1071         ogRaiseError $OG_ERR_FORMAT
1072         return $?
1073esac
1074
1075# Montar el sistema de archivos.
1076MNTDIR=$(ogMount $1 $2) || return $?
1077
1078ETC=$(ogGetPath $1 $2 /etc)
1079
1080if [ -d "$ETC" ]; then
1081        #cambio de nombre en hostname
1082        echo "$NAME" > $ETC/hostname
1083        #Opcion A para cambio de nombre en hosts
1084        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
1085        #Opcion B componer fichero de hosts
1086        cat > $ETC/hosts <<EOF
1087127.0.0.1       localhost
1088127.0.1.1       $NAME
1089
1090# The following lines are desirable for IPv6 capable hosts
1091::1     ip6-localhost ip6-loopback
1092fe00::0 ip6-localnet
1093ff00::0 ip6-mcastprefix
1094ff02::1 ip6-allnodes
1095ff02::2 ip6-allrouters
1096EOF
1097fi
1098}
1099
1100
1101
1102#/**
1103#         ogCleanLinuxDevices int_ndisk int_nfilesys
1104#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
1105#@param   int_ndisk      nº de orden del disco
1106#@param   int_nfilesys   nº de orden del sistema de archivos
1107#@return  (nada)
1108#@exception OG_ERR_FORMAT    Formato incorrecto.
1109#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1110#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
1111#@version 1.0.5 - Primera versión para OpenGnSys.
1112#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1113#@date    2013-03-21
1114#@version 1.0.6b - Elimina fichero resume de hibernacion
1115#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1116#@date    2016-11-07
1117#*/ ##
1118function ogCleanLinuxDevices ()
1119{
1120# Variables locales.
1121local MNTDIR
1122
1123# Si se solicita, mostrar ayuda.
1124if [ "$*" == "help" ]; then
1125    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1126           "$FUNCNAME 1 1"
1127    return
1128fi
1129# Error si no se reciben 2 parámetros.
1130[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1131
1132# Montar el sistema de archivos.
1133MNTDIR=$(ogMount $1 $2) || return $?
1134
1135# Eliminar fichero de configuración de udev para dispositivos fijos de red.
1136[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
1137# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
1138[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
1139}
1140
1141#/**
1142# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
1143#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1144#@param 1 Numero de disco
1145#@param 2 Numero de particion
1146#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1147#@param 4 offline  configura el modo offline [offline|online] (opcional)
1148#@return  (nada)
1149#@exception OG_ERR_FORMAT    Formato incorrecto.
1150#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1151#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1152# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
1153#@version 1.0.6 - Prmera integración
1154#@author 
1155#@date    2016-11-07
1156#@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.
1157#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1158#@date    2017-06-17
1159#*/ ##
1160
1161
1162function ogGrubAddOgLive ()
1163{
1164    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
1165
1166    # Si se solicita, mostrar ayuda.
1167    if [ "$*" == "help" ]; then
1168        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1169                "$FUNCNAME 1 1" \
1170                "$FUNCNAME 1 6 15 offline"
1171        return
1172    fi
1173
1174    # Error si no se reciben 2 parámetros.
1175    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
1176    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
1177
1178    # Error si no existe el kernel y el initrd en la cache.
1179    # Falta crear nuevo codigo de error.
1180    [ -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 $?)
1181
1182    # Archivo de configuracion del grub
1183    DIRMOUNT=$(ogMount $1 $2)
1184    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1185
1186    # Error si no existe archivo del grub
1187    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1188
1189    # Si existe la entrada de opengnsys, se borra
1190    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
1191
1192    # Tipo de tabla de particiones
1193    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1194
1195    # Localizacion de la cache
1196    read NUMDISK NUMPART <<< $(ogFindCache)
1197    let NUMDISK=$NUMDISK-1
1198    # kernel y sus opciones. Pasamos a modo usuario
1199    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
1200
1201    # Configuracion offline si existe parametro
1202    echo "$@" |grep offline &>/dev/null && STATUS=offline
1203    echo "$@" |grep online  &>/dev/null && STATUS=online
1204    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1205
1206    # Numero de línea de la primera entrada del grub.
1207    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1208    # Texto de la entrada de opengnsys
1209MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
1210\tinsmod part_$PARTTABLETYPE \n \
1211\tinsmod ext2 \n \
1212\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1213\tlinux $KERNEL \n \
1214\tinitrd /boot/${oglivedir}/oginitrd.img \n \
1215}"
1216
1217
1218    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1219    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1220
1221    # Ponemos que la entrada por defecto sea la primera.
1222    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1223
1224    # Si me dan valor para timeout lo cambio en el grub.
1225    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1226}
1227
1228#/**
1229# ogGrubHidePartitions num_disk num_part
1230#@brief ver ogBootLoaderHidePartitions
1231#@see ogBootLoaderHidePartitions
1232#*/ ##
1233function ogGrubHidePartitions ()
1234{
1235    # Si se solicita, mostrar ayuda.
1236    if [ "$*" == "help" ]; then
1237        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1238               "$FUNCNAME 1 6"
1239        return
1240    fi
1241    ogBootLoaderHidePartitions $@
1242    return $?
1243}
1244
1245#/**
1246# ogBurgHidePartitions num_disk num_part
1247#@brief ver ogBootLoaderHidePartitions
1248#@see ogBootLoaderHidePartitions
1249#*/ ##
1250function ogBurgHidePartitions ()
1251{
1252    # Si se solicita, mostrar ayuda.
1253    if [ "$*" == "help" ]; then
1254        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1255               "$FUNCNAME 1 6"
1256        return
1257    fi
1258    ogBootLoaderHidePartitions $@
1259    return $?
1260}
1261
1262#/**
1263# ogBootLoaderHidePartitions num_disk num_part
1264#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
1265#@param 1 Numero de disco
1266#@param 2 Numero de particion
1267#@return  (nada)
1268#@exception OG_ERR_FORMAT    Formato incorrecto.
1269#@exception No existe archivo de configuracion del grub/burg.
1270#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1271#@author  Irina Gomez, ETSII Universidad de Sevilla
1272#@date    2015-11-17
1273#@version 1.1 Se generaliza la función para grub y burg
1274#@author  Irina Gomez, ETSII Universidad de Sevilla
1275#@date    2017-10-20
1276#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1277#@author  Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
1278#@date    2018-07-05
1279#*/
1280
1281function ogBootLoaderHidePartitions ()
1282{
1283    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1284
1285    # Si se solicita, mostrar ayuda.
1286    if [ "$*" == "help" ]; then
1287        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
1288        return
1289    fi
1290
1291    # Nombre de la función que llama a esta.
1292    FUNC="${FUNCNAME[@]:1}"
1293    FUNC="${FUNC%%\ *}"
1294
1295    # Error si no se reciben 2 parámetros.
1296    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1297
1298    # Archivo de configuracion del grub
1299    DIRMOUNT=$(ogMount $1 $2)
1300    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1301    case "$FUNC" in
1302        ogGrubHidePartitions)
1303            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1304            ;;
1305        ogBurgHidePartitions)
1306            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1307            ;;
1308        *)
1309            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1310            return $?
1311            ;;
1312    esac
1313
1314    # Error si no existe archivo del grub
1315    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
1316
1317    # Si solo hay una particion de Windows me salgo
1318    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
1319
1320    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
1321    sed -i '/parttool/d' $CFGFILE
1322
1323    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1324#   /*  (comentario de bloque para  Doxygen)
1325    # Entradas de Windows: numero de linea y particion. De mayor a menor.
1326    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
1327    #*/ (comentario para bloque Doxygen)
1328    # Particiones de Windows, pueden no estar en el grub.
1329    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
1330    # Modifico todas las entradas de Windows.
1331    for ENTRY in $WINENTRY; do
1332        LINE=${ENTRY%:*}
1333        PART=${ENTRY#*:}
1334        # En cada entrada, oculto o muestro cada particion.
1335        TEXT=""
1336        for PART2 in $WINPART; do
1337                # Muestro solo la particion de la entrada actual.
1338                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
1339
1340                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
1341        done
1342       
1343        sed -i "${LINE}a\ $TEXT" $CFGFILE
1344    done
1345
1346    # Activamos la particion que se inicia en todas las entradas de windows.
1347    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
1348
1349}
1350
1351#/**
1352# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
1353#@brief ver ogBootLoaderDeleteEntry
1354#@see ogBootLoaderDeleteEntry
1355#*/
1356function ogGrubDeleteEntry ()
1357{
1358    # Si se solicita, mostrar ayuda.
1359    if [ "$*" == "help" ]; then
1360        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1361                "$FUNCNAME 1 6 2 1"
1362        return
1363    fi
1364    ogBootLoaderDeleteEntry $@
1365    return $?
1366}
1367
1368#/**
1369# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
1370#@brief ver ogBootLoaderDeleteEntry
1371#@see ogBootLoaderDeleteEntry
1372#*/
1373function ogBurgDeleteEntry ()
1374{
1375    # Si se solicita, mostrar ayuda.
1376    if [ "$*" == "help" ]; then
1377        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1378                "$FUNCNAME 1 6 2 1"
1379        return
1380    fi
1381    ogBootLoaderDeleteEntry $@
1382    return $?
1383}
1384
1385#/**
1386# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1387#@brief Borra en el grub las entradas para el inicio en una particion.
1388#@param 1 Numero de disco donde esta el grub
1389#@param 2 Numero de particion donde esta el grub
1390#@param 3 Numero del disco del que borramos las entradas
1391#@param 4 Numero de la particion de la que borramos las entradas
1392#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
1393#@return  (nada)
1394#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1395#@exception OG_ERR_FORMAT    Formato incorrecto.
1396#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1397#@version 1.1 Se generaliza la función para grub y burg
1398#@author  Irina Gomez, ETSII Universidad de Sevilla
1399#@date    2017-10-20
1400#*/ ##
1401
1402function ogBootLoaderDeleteEntry ()
1403{
1404    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
1405
1406    # Si se solicita, mostrar ayuda.
1407    if [ "$*" == "help" ]; then
1408        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1409        return
1410    fi
1411
1412    # Si el número de parámetros menos que 4 nos salimos
1413    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1414 
1415
1416    # Nombre de la función que llama a esta.
1417    FUNC="${FUNCNAME[@]:1}"
1418    FUNC="${FUNC%%\ *}"
1419
1420    # Archivo de configuracion del grub
1421    DIRMOUNT=$(ogMount $1 $2)
1422    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1423    case "$FUNC" in
1424        ogGrubDeleteEntry)
1425            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1426            ;;
1427        ogBurgDeleteEntry)
1428            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1429            ;;
1430        *)
1431            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1432            return $?
1433            ;;
1434    esac
1435
1436    # Dispositivo
1437    DEVICE=$(ogDiskToDev $3 $4)
1438
1439    # Error si no existe archivo del grub)
1440    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
1441
1442    # Numero de linea de cada entrada.
1443    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1444
1445    # Entradas que hay que borrar.
1446    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1447
1448    # Si no hay entradas para borrar me salgo con aviso
1449    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
1450
1451    # Recorremos el fichero del final hacia el principio.
1452    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1453    for ENTRY in $MENUENTRY; do
1454        # Comprobamos si hay que borrar la entrada.
1455        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1456            let ENDENTRY=$ENDENTRY-1
1457            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1458        fi
1459
1460        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1461        ENDENTRY=$ENTRY
1462    done
1463}
1464
1465#/**
1466#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1467#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1468#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1469#@param   int_disk_SecondStage     
1470#@param   int_part_SecondStage     
1471#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1472#@return 
1473#@exception OG_ERR_FORMAT    Formato incorrecto.
1474#@exception OG_ERR_PARTITION  Partición no soportada
1475#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1476#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1477#@date    2017-06-23
1478#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1479#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1480#@date    2018-01-21
1481#@version 1.1.0 - Refactorizar fichero de configuacion
1482#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1483#@date    2018-01-24
1484#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1485#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1486#@date    2018-07-05
1487#*/ ##
1488
1489function ogBurgInstallMbr ()
1490{
1491 
1492# Variables locales.
1493local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1494
1495# Si se solicita, mostrar ayuda.
1496if [ "$*" == "help" ]; then
1497    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1498           "$FUNCNAME 1 1 FALSE " \
1499           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1500    return
1501fi 
1502
1503# Error si no se reciben 2 parametros.
1504[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1505
1506
1507DISK=$1; PART=$2;
1508CHECKOS=${3:-"FALSE"}
1509KERNELPARAM=$4
1510BACKUPNAME=".backup.og"
1511
1512#Error si no es linux.
1513ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1514
1515
1516#La primera etapa del grub se fija en el primer disco duro
1517FIRSTSTAGE=$(ogDiskToDev 1)
1518
1519#localizar disco segunda etapa del grub
1520SECONDSTAGE=$(ogMount $DISK $PART)
1521
1522# prepara el directorio principal de la segunda etapa (y copia los binarios)
1523[ -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)
1524
1525#Copiamos el tema
1526mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1527cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
1528
1529#Localizar directorio segunda etapa del grub   
1530#PREFIXSECONDSTAGE="/boot/burg/"
1531
1532# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1533if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1534then
1535    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1536    then
1537        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1538        return $?
1539    fi
1540fi
1541
1542# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1543
1544#llamada a updateBootCache para que aloje la primera fase del ogLive
1545updateBootCache
1546
1547#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1548echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1549echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1550
1551
1552#Preparar configuración segunda etapa: crear ubicacion
1553mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1554
1555#Preparar configuración segunda etapa: crear cabecera del fichero
1556#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1557
1558FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1559
1560#/* ## (comentario Dogygen)
1561cat > "$FILECFG" << EOF
1562
1563set theme_name=OpenGnsys
1564set gfxmode=1024x768
1565
1566
1567set locale_dir=(\$root)/boot/burg/locale
1568
1569set default=0
1570set timeout=25
1571set lang=es
1572
1573
1574insmod ext2
1575insmod gettext
1576
1577
1578
1579
1580if [ -s \$prefix/burgenv ]; then
1581  load_env
1582fi
1583
1584
1585
1586if [ \${prev_saved_entry} ]; then
1587  set saved_entry=\${prev_saved_entry}
1588  save_env saved_entry
1589  set prev_saved_entry=
1590  save_env prev_saved_entry
1591  set boot_once=true
1592fi
1593
1594function savedefault {
1595  if [ -z \${boot_once} ]; then
1596    saved_entry=\${chosen}
1597    save_env saved_entry
1598  fi
1599}
1600function select_menu {
1601  if menu_popup -t template_popup theme_menu ; then
1602    free_config template_popup template_subitem menu class screen
1603    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1604    save_env theme_name
1605    menu_refresh
1606  fi
1607}
1608
1609function toggle_fold {
1610  if test -z $theme_fold ; then
1611    set theme_fold=1
1612  else
1613    set theme_fold=
1614  fi
1615  save_env theme_fold
1616  menu_refresh
1617}
1618function select_resolution {
1619  if menu_popup -t template_popup resolution_menu ; then
1620    menu_reload_mode
1621    save_env gfxmode
1622  fi
1623}
1624
1625
1626if test -f \${prefix}/themes/\${theme_name}/theme ; then
1627  insmod coreui
1628  menu_region.text
1629  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1630  load_config \${prefix}/themes/conf.d/10_hotkey   
1631  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1632  insmod vbe
1633  insmod png
1634  insmod jpeg
1635  set gfxfont="Unifont Regular 16"
1636  menu_region.gfx
1637  vmenu resolution_menu
1638  controller.ext
1639fi
1640
1641
1642EOF
1643#*/ ## (comentario Dogygen)
1644
1645#Preparar configuración segunda etapa: crear entrada del sistema operativo
1646grubSyntax "$KERNELPARAM" >> "$FILECFG"
1647
1648
1649#Instalar el burg
1650burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
1651}
1652
1653#/**
1654# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1655#@brief ver ogBootLoaderDefaultEntry
1656#@see ogBootLoaderDefaultEntry
1657#*/ ##
1658function ogGrubDefaultEntry ()
1659{
1660    # Si se solicita, mostrar ayuda.
1661    if [ "$*" == "help" ]; then
1662        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1663               "$FUNCNAME 1 6 1 1"
1664        return
1665    fi
1666    ogBootLoaderDefaultEntry $@
1667    return $?
1668}
1669
1670#/**
1671# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1672#@brief ver ogBootLoaderDefaultEntry
1673#@see ogBootLoaderDefaultEntry
1674#*/ ##
1675function ogBurgDefaultEntry ()
1676{
1677    # Si se solicita, mostrar ayuda.
1678    if [ "$*" == "help" ]; then
1679        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1680               "$FUNCNAME 1 6 1 1"
1681        return
1682    fi
1683    ogBootLoaderDefaultEntry $@
1684    return $?
1685}
1686
1687#/**
1688# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1689#@brief   Configura la entrada por defecto de Burg
1690#@param   int_disk_SecondStage     
1691#@param   int_part_SecondStage     
1692#@param   int_disk_default_entry
1693#@param   int_part_default_entry
1694#@return 
1695#@exception OG_ERR_FORMAT    Formato incorrecto.
1696#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1697#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1698#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1699#@version 1.1.0 - Define la entrada por defecto del Burg
1700#@author  Irina Gomez, ETSII Universidad de Sevilla
1701#@date    2017-08-09
1702#@version 1.1 Se generaliza la función para grub y burg
1703#@author  Irina Gomez, ETSII Universidad de Sevilla
1704#@date    2018-01-04
1705#*/ ##
1706function ogBootLoaderDefaultEntry ()
1707{
1708
1709# Variables locales.
1710local PART CFGFILE DEFAULTENTRY MSG
1711
1712# Si se solicita, mostrar ayuda.
1713if [ "$*" == "help" ]; then
1714    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
1715    return
1716fi 
1717
1718# Nombre de la función que llama a esta.
1719FUNC="${FUNCNAME[@]:1}"
1720FUNC="${FUNC%%\ *}"
1721
1722# Error si no se reciben 3 parametros.
1723[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1724
1725# Error si no puede montar sistema de archivos.
1726DIRMOUNT=$(ogMount $1 $2) || return $?
1727
1728# Comprobamos que exista fichero de configuración
1729# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1730case "$FUNC" in
1731    ogGrubDefaultEntry)
1732        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1733        ;;
1734    ogBurgDefaultEntry)
1735        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1736        ;;
1737    *)
1738        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1739        return $?
1740        ;;
1741esac
1742
1743# Error si no existe archivo de configuración
1744[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1745
1746# Dispositivo
1747DEVICE=$(ogDiskToDev $3 $4)
1748
1749# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1750DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1751
1752# Si no hay entradas para borrar me salgo con aviso
1753[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
1754
1755# Número de la de linea por defecto en el menú de usuario
1756MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1757# Las líneas empiezan a contar desde cero
1758let MENUENTRY=$MENUENTRY-1
1759sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1760MSG="MSG_HELP_$FUNC"
1761echo "${!MSG%%\.}: $@"
1762}
1763
1764#/**
1765# ogGrubOgliveDefaultEntry num_disk num_part
1766#@brief ver ogBootLoaderOgliveDefaultEntry
1767#@see ogBootLoaderOgliveDefaultEntry
1768#*/ ##
1769function ogGrubOgliveDefaultEntry ()
1770{
1771    # Si se solicita, mostrar ayuda.
1772    if [ "$*" == "help" ]; then
1773        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1774               "$FUNCNAME 1 6"
1775        return
1776    fi
1777    ogBootLoaderOgliveDefaultEntry $@
1778    return $?
1779}
1780
1781#/**
1782# ogBurgOgliveDefaultEntry num_disk num_part
1783#@brief ver ogBootLoaderOgliveDefaultEntry
1784#@see ogBootLoaderOgliveDefaultEntry
1785#*/ ##
1786function ogBurgOgliveDefaultEntry ()
1787{
1788    # Si se solicita, mostrar ayuda.
1789    if [ "$*" == "help" ]; then
1790        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1791               "$FUNCNAME 1 6"
1792        return
1793    fi
1794    ogBootLoaderOgliveDefaultEntry $@
1795    return $?
1796}
1797
1798#/**
1799# ogBootLoaderOgliveDefaultEntry
1800#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1801#@param   int_disk_SecondStage     
1802#@param   int_part_SecondStage     
1803#@return 
1804#@exception OG_ERR_FORMAT    Formato incorrecto.
1805#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1806#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1807#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1808#@version 1.1.0 - Primeras pruebas con Burg
1809#@author  Irina Gomez, ETSII Universidad de Sevilla
1810#@date    2017-08-09
1811#@version 1.1 Se generaliza la función para grub y burg
1812#@author  Irina Gomez, ETSII Universidad de Sevilla
1813#@date    2018-01-04
1814#*/ ##
1815function  ogBootLoaderOgliveDefaultEntry ()
1816{
1817
1818# Variables locales.
1819local FUNC PART CFGFILE NUMENTRY MSG
1820
1821# Si se solicita, mostrar ayuda.
1822if [ "$*" == "help" ]; then
1823    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
1824    return
1825fi 
1826
1827# Nombre de la función que llama a esta.
1828FUNC="${FUNCNAME[@]:1}"
1829FUNC="${FUNC%%\ *}"
1830
1831# Error si no se reciben 2 parametros.
1832[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1833
1834# Error si no puede montar sistema de archivos.
1835PART=$(ogMount $1 $2) || return $?
1836# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1837case "$FUNC" in
1838    ogGrubOgliveDefaultEntry)
1839        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1840        ;;
1841    ogBurgOgliveDefaultEntry)
1842        CFGFILE="$PART/boot/burg/burg.cfg"
1843        ;;
1844    *)
1845        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1846        return $?
1847        ;;
1848esac
1849
1850# Comprobamos que exista fichero de configuración
1851[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1852
1853# Detectamos cual es la entrada de ogLive
1854NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
1855
1856# Si no existe entrada de ogLive nos salimos
1857[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
1858
1859let NUMENTRY=$NUMENTRY-1
1860sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
1861
1862MSG="MSG_HELP_$FUNC"
1863echo "${!MSG%%\.}: $@"
1864}
1865
1866
1867#/**
1868# ogGrubSetTheme num_disk num_part str_theme
1869#@brief ver ogBootLoaderSetTheme
1870#@see ogBootLoaderSetTheme
1871#*/ ##
1872function ogGrubSetTheme ()
1873{
1874    # Si se solicita, mostrar ayuda.
1875    if [ "$*" == "help" ]; then
1876        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1877               "$FUNCNAME 1 4 ThemeBasic"\
1878               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1879        return
1880    fi
1881    ogBootLoaderSetTheme $@
1882    return $?
1883}
1884
1885#/**
1886# ogBurgSetTheme num_disk num_part str_theme
1887#@brief ver ogBootLoaderSetTheme
1888#@see ogBootLoaderSetTheme
1889#*/ ##
1890function ogBurgSetTheme  ()
1891{
1892    # Si se solicita, mostrar ayuda.
1893    if [ "$*" == "help" ]; then
1894        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1895               "$FUNCNAME 1 4 ThemeBasic" \
1896               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1897        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
1898               
1899        return
1900    fi
1901    ogBootLoaderSetTheme $@
1902    return $?
1903}
1904
1905
1906
1907#/**
1908# ogBootLoaderSetTheme
1909#@brief   asigna un tema al BURG
1910#@param   int_disk_SecondStage     
1911#@param   int_part_SecondStage 
1912#@param   str_theme_name   
1913#@return 
1914#@exception OG_ERR_FORMAT    Formato incorrecto.
1915#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1916#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
1917#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
1918#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
1919#@author  Antonio J. Doblas Viso. Universidad de Malaga
1920#@date    2018-01-24
1921#*/ ##
1922function  ogBootLoaderSetTheme ()
1923{
1924
1925# Variables locales.
1926local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG
1927
1928# Si se solicita, mostrar ayuda.
1929if [ "$*" == "help" ]; then
1930    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme"
1931    return   
1932fi
1933 
1934
1935NEWTHEME="$3"
1936
1937# Nombre de la función que llama a esta.
1938FUNC="${FUNCNAME[@]:1}"
1939FUNC="${FUNC%%\ *}"
1940
1941
1942
1943# Error si no se reciben 2 parametros.
1944[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
1945
1946# Error si no puede montar sistema de archivos.
1947PART=$(ogMount $1 $2) || return $?
1948# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme.
1949case "$FUNC" in
1950    ogGrubSetTheme)
1951        BOOTLOADER="grug"
1952        BOOTLOADERDIR="grubMBR"
1953        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
1954        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
1955        return $?               
1956        ;;
1957    ogBurgSetTheme)
1958        BOOTLOADER="burg"
1959        BOOTLOADERDIR="burg"
1960        CFGFILE="$PART/boot/burg/burg.cfg"       
1961        ;;
1962    *)
1963        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme or ogBurgSetTheme."
1964        return $?
1965        ;;
1966esac
1967
1968# Comprobamos que exista fichero de configuración
1969[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1970
1971# Detectamos cual es el tema asignado
1972THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
1973
1974# Si no existe entrada de theme_name  nos salimos
1975[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
1976
1977#Actualizamos el tema del servidor a la particion
1978if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
1979        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/boot/$BOOTLOADERDIR/themes/   
1980fi
1981
1982#Verificamos que el tema esta en la particion
1983if ! [ -d $PART/boot/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
1984                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/boot/$BOOTLOADERDIR/themes/" || return $?
1985fi
1986
1987#Cambiamos la entrada el fichero de configuración.
1988sed --regexp-extended -i  s/"$THEME"/"$NEWTHEME"/g $CFGFILE
1989
1990
1991}
1992
1993#/**
1994# ogGrubSetAdminKeys num_disk num_part str_theme
1995#@brief ver ogBootLoaderSetTheme
1996#@see ogBootLoaderSetTheme
1997#*/ ##
1998function ogGrubSetAdminKeys ()
1999{
2000    # Si se solicita, mostrar ayuda.
2001    if [ "$*" == "help" ]; then
2002        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2003               "$FUNCNAME 1 4 FALSE "\
2004               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2005        return
2006    fi
2007    ogBootLoaderSetAdminKeys $@
2008    return $?
2009}
2010
2011#/**
2012# ogBurgSetAdminKeys num_disk num_part str_bolean
2013#@brief ver ogBootLoaderSetAdminKeys
2014#@see ogBootLoaderSetAdminKeys
2015#*/ ##
2016function ogBurgSetAdminKeys  ()
2017{
2018    # Si se solicita, mostrar ayuda.
2019    if [ "$*" == "help" ]; then
2020        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2021               "$FUNCNAME 1 4 TRUE" \
2022               "$FUNCNAME \$(ogFindCache) FALSE"               
2023        return
2024    fi
2025    ogBootLoaderSetAdminKeys $@
2026    return $?
2027}
2028
2029
2030
2031#/**
2032# ogBootLoaderSetAdminKeys
2033#@brief   Activa/Desactica las teclas de administracion
2034#@param   int_disk_SecondStage     
2035#@param   int_part_SecondStage 
2036#@param   Boolean TRUE/FALSE   
2037#@return 
2038#@exception OG_ERR_FORMAT    Formato incorrecto.
2039#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2040#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2041#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2042#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2043#@author  Antonio J. Doblas Viso. Universidad de Malaga
2044#@date    2018-01-24
2045#*/ ##
2046function  ogBootLoaderSetAdminKeys ()
2047{
2048
2049# Variables locales.
2050local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2051
2052# Si se solicita, mostrar ayuda.
2053if [ "$*" == "help" ]; then
2054    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2055    return   
2056fi
2057 
2058
2059# Nombre de la función que llama a esta.
2060FUNC="${FUNCNAME[@]:1}"
2061FUNC="${FUNC%%\ *}"
2062
2063
2064# Error si no se reciben 2 parametros.
2065[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2066
2067# Error si no puede montar sistema de archivos.
2068PART=$(ogMount $1 $2) || return $?
2069# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2070case "$FUNC" in
2071    ogGrubSetAdminKeys)
2072        BOOTLOADER="grug"
2073        BOOTLOADERDIR="grubMBR"
2074        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2075        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2076        return $?       
2077        ;;
2078    ogBurgSetAdminKeys)
2079        BOOTLOADER="burg"
2080        BOOTLOADERDIR="burg"
2081        CFGFILE="$PART/boot/burg/burg.cfg"       
2082        ;;
2083    *)
2084        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2085        return $?
2086        ;;
2087esac
2088
2089
2090# Comprobamos que exista fichero de configuración
2091[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2092
2093
2094case "$3" in
2095        true|TRUE)
2096                [ -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
2097        ;;
2098        false|FALSE)
2099                [ -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
2100        ;;     
2101        *)
2102           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2103        return $?
2104    ;; 
2105esac
2106}
2107
2108
2109
2110#/**
2111# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
2112#@brief ver ogBootLoaderSetTimeOut
2113#@see ogBootLoaderSetTimeOut
2114#*/ ##
2115function ogGrubSetTimeOut ()
2116{
2117    # Si se solicita, mostrar ayuda.
2118    if [ "$*" == "help" ]; then
2119        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2120               "$FUNCNAME 1 4 50 "\
2121               "$FUNCNAME \$(ogFindCache) 50"
2122        return
2123    fi
2124    ogBootLoaderSetTimeOut $@
2125    return $?
2126}
2127
2128#/**
2129# ogBurgSetTimeOut num_disk num_part str_bolean
2130#@brief ver ogBootLoaderSetTimeOut
2131#@see ogBootLoaderSetTimeOut
2132#*/ ##
2133function ogBurgSetTimeOut ()
2134{
2135    # Si se solicita, mostrar ayuda.
2136    if [ "$*" == "help" ]; then
2137        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2138               "$FUNCNAME 1 4 50" \
2139               "$FUNCNAME \$(ogFindCache) 50"               
2140        return
2141    fi
2142    ogBootLoaderSetTimeOut $@
2143    return $?
2144}
2145
2146
2147
2148#/**
2149# ogBootLoaderSetTimeOut
2150#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2151#@param   int_disk_SecondStage     
2152#@param   int_part_SecondStage 
2153#@param   int_timeout_seconds   
2154#@return 
2155#@exception OG_ERR_FORMAT    Formato incorrecto.
2156#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2157#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2158#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2159#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2160#@author  Antonio J. Doblas Viso. Universidad de Malaga
2161#@date    2018-01-24
2162#*/ ##
2163function  ogBootLoaderSetTimeOut ()
2164{
2165
2166# Variables locales.
2167local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2168
2169# Si se solicita, mostrar ayuda.
2170if [ "$*" == "help" ]; then
2171    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut"
2172    return   
2173fi
2174 
2175ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2176
2177# Nombre de la función que llama a esta.
2178FUNC="${FUNCNAME[@]:1}"
2179FUNC="${FUNC%%\ *}"
2180
2181# Error si no se reciben 3 parametros.
2182[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2183
2184# Error si no puede montar sistema de archivos.
2185PART=$(ogMount $1 $2) || return $?
2186# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut.
2187case "$FUNC" in
2188    ogGrubSetTimeOut)
2189        BOOTLOADER="grug"
2190        BOOTLOADERDIR="grubMBR"
2191        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2192        ;;
2193    ogBurgSetTimeOut)
2194        BOOTLOADER="burg"
2195        BOOTLOADERDIR="burg"
2196        CFGFILE="$PART/boot/burg/burg.cfg"       
2197        ;;
2198    *)
2199        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut"
2200        return $?
2201        ;;
2202esac
2203
2204# Comprobamos que exista fichero de configuración
2205[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2206
2207# Asignamos el timeOut.
2208sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2209}
2210
2211
2212#/**
2213# ogGrubSetResolution num_disk num_part int_resolution
2214#@brief ver ogBootLoaderSetResolution
2215#@see ogBootLoaderSetResolution
2216#*/ ##
2217function ogGrubSetResolution ()
2218{
2219    # Si se solicita, mostrar ayuda.
2220    if [ "$*" == "help" ]; then
2221        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2222             "$FUNCNAME 1 4 1024x768" \
2223             "$FUNCNAME \$(ogFindCache) 1024x768" \
2224             "$FUNCNAME 1 4" 
2225        return
2226    fi
2227    ogBootLoaderSetResolution $@
2228    return $?
2229}
2230
2231#/**
2232# ogBurgSetResolution num_disk num_part str_bolean
2233#@brief ver ogBootLoaderSetResolution
2234#@see ogBootLoaderSetResolution
2235#*/ ##
2236function ogBurgSetResolution ()
2237 {
2238    # Si se solicita, mostrar ayuda.
2239    if [ "$*" == "help" ]; then
2240        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2241               "$FUNCNAME 1 4 1024x768" \
2242               "$FUNCNAME \$(ogFindCache) 1024x768" \
2243               "$FUNCNAME 1 4"               
2244        return
2245    fi
2246    ogBootLoaderSetResolution $@
2247    return $?
2248}
2249
2250
2251
2252#/**
2253# ogBootLoaderSetResolution
2254#@brief   Define la resolucion que usuara el thema del gestor de arranque
2255#@param   int_disk_SecondStage     
2256#@param   int_part_SecondStage 
2257#@param   str_resolution (Opcional)   
2258#@return 
2259#@exception OG_ERR_FORMAT    Formato incorrecto.
2260#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2261#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2262#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2263#@author  Antonio J. Doblas Viso. Universidad de Malaga
2264#@date    2018-01-24
2265#*/ ##
2266function  ogBootLoaderSetResolution ()
2267{
2268
2269# Variables locales.
2270local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2271
2272# Si se solicita, mostrar ayuda.
2273if [ "$*" == "help" ]; then
2274    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution"
2275    return   
2276fi
2277
2278
2279# Nombre de la función que llama a esta.
2280FUNC="${FUNCNAME[@]:1}"
2281FUNC="${FUNC%%\ *}"
2282
2283
2284# Error si no se reciben 2 parametros.
2285[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2286
2287# Error si no puede montar sistema de archivos.
2288PART=$(ogMount $1 $2) || return $?
2289# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution.
2290case "$FUNC" in
2291    ogGrubSetResolution)
2292        BOOTLOADER="grug"
2293        BOOTLOADERDIR="grubMBR"
2294        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2295        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2296        return $?     
2297        ;;
2298    ogBurgSetResolution)
2299        BOOTLOADER="burg"
2300        BOOTLOADERDIR="burg"
2301        CFGFILE="$PART/boot/burg/burg.cfg"       
2302        ;;
2303    *)
2304        ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution"
2305        return $?
2306        ;;
2307esac
2308
2309DEFAULTRESOLUTION=1024x768
2310
2311# Comprobamos que exista fichero de configuración
2312[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2313
2314#controlar variable a consierar vga (default template) o video (menu)
2315#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2316if [ $# -eq 2 ] ; then 
2317        if [ -n $video ]; then
2318                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2319        fi
2320        if [ -n $vga ] ; then
2321        case "$vga" in
2322                788|789|814)
2323                        NEWRESOLUTION=800x600
2324                        ;;
2325                791|792|824)
2326                        NEWRESOLUTION=1024x768
2327                        ;;
2328                355)
2329                        NEWRESOLUTION=1152x864
2330                        ;;
2331                794|795|829)
2332                        NEWRESOLUTION=1280x1024
2333                        ;;
2334        esac
2335        fi
2336fi
2337
2338if [ $# -eq 3 ] ; then
2339        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2340        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"
2341fi
2342
2343# Si no existe NEWRESOLUCION  asignamos la defaulT
2344[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2345
2346#Cambiamos la entrada el fichero de configuración.
2347sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2348}
2349
2350#/**
2351#         ogRefindInstall  int_ndisk bool_autoconfig
2352#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2353#@param   int_ndisk
2354#@param   bolean_Check__auto_config   true | false[default]
2355#@return
2356#@exception OG_ERR_FORMAT    Formato incorrecto.
2357#@version 1.1.0 - Primeras pruebas.
2358#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2359#@date    2017-06-26
2360#*/ ##
2361function ogRefindInstall ()
2362{
2363
2364# Variables locales.
2365local DISK EFIDIR CONFIG EFIPARTITIONID
2366
2367
2368# Si se solicita, mostrar ayuda.
2369if [ "$*" == "help" ]; then
2370    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk boolean_autoconfig " \
2371           "$FUNCNAME 1 TRUE"
2372    return
2373fi
2374
2375# Error si no se recibe 1 parámetro.
2376[ $# -ge 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
2377
2378
2379DISK=$1
2380EFIDIR=/mnt/$(ogDiskToDev $1 1 | cut -c 6-8)$1/EFI
2381CONFIG=${2:-"FALSE"}
2382EFIPARTITIONID=$(ogGetPartitionId $1 1)
2383if [ "$EFIPARTITIONID" == "EF00" ] || [ "$EFIPARTITIONID" == "ef00" ]; then
2384    cp -pr /opt/opengnsys/lib/refind ${EFIDIR}
2385    case "$CONFIG" in
2386        FALSE)
2387        if [ -a ${EFIDIR}/ubuntu ]; then
2388            echo "menuentry \"Ubuntu\" {" >> ${EFIDIR}/refind/refind.conf
2389            echo "loader /EFI/ubuntu/grubx64.efi" >> ${EFIDIR}/refind/refind.conf
2390            echo "icon /EFI/refind/icons/os_linux.png" >> ${EFIDIR}/refind/refind.conf
2391            echo "}" >> ${EFIDIR}/refind/refind.conf
2392        fi
2393        if [ -a ${EFIDIR}/Microsoft ]; then
2394            echo "menuentry \"Windows\" {" >> ${EFIDIR}/refind/refind.conf
2395            echo "loader /EFI/Microsoft/Boot/bootmgfw.efi" >> ${EFIDIR}/refind/refind.conf
2396            echo "}" >> ${EFIDIR}/refind/refind.conf
2397        fi
2398        ;;
2399        TRUE)
2400        cp  ${EFIDIR}/refind/refind.conf.auto ${EFIDIR}/refind/refind.conf
2401        ;;
2402    esac
2403else
2404$(ogRaiseError $OG_ERR_FORMAT; echo $?)
2405fi
2406}
2407
Note: See TracBrowser for help on using the repository browser.