source: client/engine/Boot.lib @ d2c8674

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 d2c8674 was d2c8674, checked in by adv <adv@…>, 7 years ago

#853 Adaptar libreria boot.lib para doxygen

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