source: client/engine/Boot.lib @ 55fcaa6

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

#829 #796 nuevas funciones complementarias para el Burg/Grub? (ogBootLoaderSetTheme,ogBootLoaderSetAdminKeys,ogBootLoaderSetTimeOut,ogBootLoaderSetResolution)

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

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