source: client/engine/Boot.lib @ 2e98055

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-instalacionwebconsole3
Last change on this file since 2e98055 was b242c72, checked in by ramon <ramongomez@…>, 7 years ago

#802: Comprobación correcta de Kernel Linux firmado para EFI y buscar también cargador por defecto de Windows para sistemas recién instalados.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5755 a21b9725-9963-47de-94b9-378ad31fedc9

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