source: client/engine/Boot.lib @ cade8c0

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 cade8c0 was cade8c0, checked in by ramon <ramongomez@…>, 7 years ago

#730: Revisar funciones del motor de clonación sin mensajes de ayuda.

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

  • Property mode set to 100755
File size: 54.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
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~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
221                                       kern=$2;
222                                       sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
223                                      } # /* (comentario Doxygen)
224                                    }
225     $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
226     END {if (kern!="") printf("%s %s %s", kern,init,app)}
227    ' $CONFFILE
228# */ (comentario Doxygen)
229}
230
231
232#/**
233#         ogSetWindowsName int_ndisk int_nfilesys str_name
234#@brief   Establece el nombre del equipo en el registro de Windows.
235#@param   int_ndisk      nº de orden del disco
236#@param   int_nfilesys   nº de orden del sistema de archivos
237#@param   str_name       nombre asignado
238#@return  (nada)
239#@exception OG_ERR_FORMAT     Formato incorrecto.
240#@exception OG_ERR_NOTFOUND   Disco o particion no corresponden con un dispositivo.
241#@exception OG_ERR_PARTITION  Tipo de partición desconocido o no se puede montar.
242#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
243#@version 0.9 - Adaptación a OpenGnSys.
244#@author  Ramon Gomez, ETSII Universidad de Sevilla
245#@date    2009-09-24
246#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
247#@author  Ramon Gomez, ETSII Universidad de Sevilla
248#@date    2013-03-20
249#*/ ##
250function ogSetWindowsName ()
251{
252# Variables locales.
253local PART MNTDIR NAME
254
255# Si se solicita, mostrar ayuda.
256if [ "$*" == "help" ]; then
257    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
258           "$FUNCNAME 1 1 PRACTICA-PC"
259    return
260fi
261# Error si no se reciben 3 parámetros.
262[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
263# Error si el nombre supera los 15 caracteres.
264[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
265
266# Montar el sistema de archivos.
267MNTDIR=$(ogMount $1 $2) || return $?
268
269# Asignar nombre.
270NAME="$3"
271
272# Modificar datos de los valores de registro.
273ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
274ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$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\NV 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
280}
281
282
283#/**
284#         ogSetWinlogonUser int_ndisk int_npartition str_username
285#@brief   Establece el nombre de usuario por defecto en la entrada de Windows.
286#@param   int_ndisk      nº de orden del disco
287#@param   int_npartition nº de orden de la partición
288#@param   str_username   nombre de usuario por defecto
289#@return  (nada)
290#@exception OG_ERR_FORMAT    Formato incorrecto.
291#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
292#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
293#@version 0.9.2 - Adaptación a OpenGnSys.
294#@author  Ramon Gomez, ETSII Universidad de Sevilla
295#@date    2010-07-20
296#*/ ##
297function ogSetWinlogonUser ()
298{
299# Variables locales.
300local PART MNTDIR NAME
301
302# Si se solicita, mostrar ayuda.
303if [ "$*" == "help" ]; then
304    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
305           "$FUNCNAME 1 1 USUARIO"
306    return
307fi
308# Error si no se reciben 3 parámetros.
309[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
310
311# Montar el sistema de archivos.
312MNTDIR=$(ogMount $1 $2) || return $?
313
314# Asignar nombre.
315NAME="$3"
316
317# Modificar datos en el registro.
318ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
319}
320
321
322#/**
323#         ogBootMbrXP int_ndisk
324#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
325#@param   int_ndisk      nº de orden del disco
326#@return  salida del programa my-sys
327#@exception OG_ERR_FORMAT    Formato incorrecto.
328#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
329#@version 0.9 - Adaptación a OpenGnSys.
330#@author  Antonio J. Doblas Viso. Universidad de Málaga
331#@date    2009-09-24
332#*/ ##
333
334function ogBootMbrXP ()
335{
336# Variables locales.
337local DISK
338
339# Si se solicita, mostrar ayuda.
340if [ "$*" == "help" ]; then
341    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
342           "$FUNCNAME 1"
343    return
344fi
345# Error si no se recibe 1 parámetro.
346[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
347
348DISK="$(ogDiskToDev $1)" || return $?
349ms-sys -z -f $DISK
350ms-sys -m -f $DISK
351}
352
353
354#/**
355#         ogBootMbrGeneric int_ndisk
356#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
357#@param   int_ndisk      nº de orden del disco
358#@return  salida del programa my-sys
359#@exception OG_ERR_FORMAT    Formato incorrecto.
360#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
361#@version 0.9 - Adaptación a OpenGnSys.
362#@author  Antonio J. Doblas Viso. Universidad de Málaga
363#@date    2009-09-24
364#*/ ##
365
366function ogBootMbrGeneric ()
367{
368# Variables locales.
369local DISK
370
371# Si se solicita, mostrar ayuda.
372if [ "$*" == "help" ]; then
373    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
374           "$FUNCNAME 1 "
375    return
376fi
377# Error si no se recibe 1 parámetro.
378[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
379
380DISK="$(ogDiskToDev $1)" || return $?
381ms-sys -z -f $DISK
382ms-sys -s -f $DISK
383}
384
385
386
387
388#/**
389#         ogFixBootSector int_ndisk int_parition
390#@brief   Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
391#@param   int_ndisk      nº de orden del disco
392#@param   int_partition     nº de particion
393#@return 
394#@exception OG_ERR_FORMAT    Formato incorrecto.
395#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
396#@version 0.9 - Adaptación a OpenGnSys.
397#@author  Antonio J. Doblas Viso. Universidad de Málaga
398#@date    2009-09-24
399#*/ ##
400
401function ogFixBootSector ()
402{
403# Variables locales.
404local PARTYPE DISK PART FILE
405
406# Si se solicita, mostrar ayuda.
407if [ "$*" == "help" ]; then
408    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
409           "$FUNCNAME 1 1 "
410    return
411fi
412
413# Error si no se reciben 2 parámetros.
414[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
415
416#TODO, solo si la particion existe
417#TODO, solo si es ntfs o fat
418PARTYPE=$(ogGetPartitionId $1 $2)
419case "$PARTYPE" in
420        1|4|6|7|b|c|e|f|17|700)
421        ;;
422        *)
423        return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
424        ;;
425esac
426
427ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
428
429#Preparando instruccion
430let DISK=$1-1   
431PART=$2
432FILE=/tmp/temp$$
433cat > $FILE <<EOF
434disk=$DISK
435main_part=$PART
436fix_first_sector=yes
437EOF
438
439spartlnx.run -cui -nm -a -f $FILE &
440sleep 5
441ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
442rm -f $FILE
443}
444
445
446
447#/**
448#         ogWindowsBootParameters int_ndisk int_parition
449#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
450#@param   int_ndisk      nº de orden del disco
451#@param   int_partition     nº de particion
452#@return 
453#@exception OG_ERR_FORMAT    Formato incorrecto.
454#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
455#@version 0.9 - Integración desde EAC para OpenGnSys.
456#@author  Antonio J. Doblas Viso. Universidad de Málaga
457#@date    2009-09-24
458#@version 1.0.1 - Adapatacion para OpenGnsys.
459#@author  Antonio J. Doblas Viso. Universidad de Málaga
460#@date    2011-05-20
461#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
462#@author  Ramon Gomez, ETSII Universidad de Sevilla
463#@date    2014-01-28
464#@version 1.1.0 - Soporte para Windows 10.
465#@author  Ramon Gomez, ETSII Universidad de Sevilla
466#@date    2016-01-19
467#*/ ##
468
469function ogWindowsBootParameters ()
470{
471# Variables locales.
472local PART DISK FILE WINVER MOUNT
473
474# Si se solicita, mostrar ayuda.
475if [ "$*" == "help" ]; then
476    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
477           "$FUNCNAME 1 1 "
478    return
479fi
480
481# Error si no se reciben 2 parámetros.
482[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
483
484ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
485
486#Preparando variables adaptadas a sintaxis windows.
487let DISK=$1-1
488PART=$2
489FILE=/tmp/temp$$
490
491# Obtener versión de Windows.
492WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
493[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?)
494
495# Acciones para Windows XP.
496if [[ "$WINVER" =~ "XP" ]]; then
497    MOUNT=$(ogMount $1 $2)
498    [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?)
499    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
500    return 0
501fi
502
503ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
504
505
506#Preparando instruccion Windows Resume Application
507cat > $FILE <<EOF
508boot_disk=$DISK
509boot_main_part=$PART
510disk=$DISK
511main_part=$PART
512boot_entry=Windows Resume Application
513EOF
514spartlnx.run -cui -nm -w -f $FILE &
515sleep 5
516ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
517
518 
519
520#Preparando instruccion tipo windows
521cat > $FILE <<EOF
522boot_disk=$DISK
523boot_main_part=$PART
524disk=$DISK
525main_part=$PART
526boot_entry=$WINVER
527EOF
528spartlnx.run -cui -nm -w -f $FILE &
529sleep 5
530ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
531
532
533##Preparando instruccion        Ramdisk Options
534cat > $FILE <<EOF
535boot_disk=$DISK
536boot_main_part=$PART
537disk=$DISK
538main_part=$PART
539boot_entry=Ramdisk Options
540EOF
541spartlnx.run -cui -nm -w -f $FILE &
542sleep 5
543ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
544
545
546#Preparando instruccion Windows Boot Manager
547cat > $FILE <<EOF
548boot_disk=$DISK
549boot_main_part=$PART
550disk=$DISK
551main_part=$PART
552boot_entry=Windows Boot Manager
553EOF
554spartlnx.run -cui -nm -w -f $FILE &
555sleep 5
556ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
557
558
559#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
560cat > $FILE <<EOF
561boot_disk=$DISK
562boot_main_part=$PART
563disk=$DISK
564main_part=$PART
565boot_entry=Herramienta de diagnóstico de memoria de Windows
566EOF
567spartlnx.run -cui -nm -w -f $FILE &
568sleep 5
569ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
570
571}
572
573
574#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
575#@brief   Registra una partición en windows con un determinado volumen.
576#@param   int_ndisk      nº de orden del disco a registrar
577#@param   int_partition     nº de particion a registrar
578#@param   str_volumen      volumen a resgistar
579#@param   int_ndisk_windows      nº de orden del disco donde esta windows
580#@param   int_partition_windows     nº de particion donde esta windows
581#@return 
582#@exception OG_ERR_FORMAT    Formato incorrecto.
583#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
584#@version 0.9 - Adaptación a OpenGnSys.
585#@author  Antonio J. Doblas Viso. Universidad de Málaga
586#@date    2009-09-24
587#*/ ##
588function ogWindowsRegisterPartition ()
589{
590# Variables locales.
591local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
592
593# Si se solicita, mostrar ayuda.
594if [ "$*" == "help" ]; then
595    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
596           "$FUNCNAME 1 1 c: 1 1"
597    return
598fi
599
600# Error si no se reciben 5 parámetros.
601[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
602
603REGISTREDDISK=$1
604REGISTREDPART=$2
605REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
606DISK=$4
607PART=$5
608FILE=/tmp/temp$$
609
610ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
611ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
612
613ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
614
615VERSION=$(ogGetOsVersion $DISK $PART)
616
617#Systemroot
618
619if ogGetPath $DISK $PART WINDOWS
620then
621        SYSTEMROOT="Windows"
622elif ogGetPath $DISK $PART WINNT
623then
624        SYSTEMROOT="winnt"
625else
626        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
627fi
628
629ogUnmount $DISK $PART
630let DISK=$DISK-1
631let REGISTREDDISK=$REGISTREDDISK-1
632#Preparando instruccion Windows Boot Manager
633cat > $FILE <<EOF
634windows_disk=$DISK
635windows_main_part=$PART
636windows_dir=$SYSTEMROOT
637disk=$REGISTREDDISK
638main_part=$REGISTREDPART
639;ext_part
640part_letter=$REGISTREDVOL
641EOF
642spartlnx.run -cui -nm -u -f $FILE &
643sleep 5
644ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
645
646}
647
648
649#         ogGrubInstallMbr  int_disk_GRUBCFG  int_partition_GRUBCFG 
650#@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.
651#@param   int_disk_SecondStage     
652#@param   int_part_SecondStage     
653#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
654#@return 
655#@exception OG_ERR_FORMAT    Formato incorrecto.
656#@version 1.0.2 - Primeras pruebas.
657#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
658#@date    2011-10-29
659#@version 1.0.3 - Soporte para linux de 32 y 64 bits
660#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
661#@date    2012-03-13
662#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
663#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
664#@date    2012-03-13
665#@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.
666#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
667#@date    2017-06-19
668#*/ ##
669
670function ogGrubInstallMbr {
671
672# Variables locales.
673local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
674
675# Si se solicita, mostrar ayuda.
676if [ "$*" == "help" ]; then
677    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
678           "$FUNCNAME 1 1 FALSE " \
679           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
680    return
681fi 
682
683# Error si no se reciben 2 parámetros.
684[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
685
686
687DISK=$1; PART=$2;
688CHECKOS=${3:-"FALSE"}
689KERNELPARAM=$4
690BACKUPNAME=".backup.og"
691
692#Error si no es linux.
693#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
694#VERSION=$(ogGetOsVersion $DISK $PART)
695#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
696
697#La primera etapa del grub se fija en el primer disco duro
698FIRSTSTAGE=$(ogDiskToDev 1)
699
700#localizar disco segunda etapa del grub
701SECONDSTAGE=$(ogMount $DISK $PART)
702
703# prepara el directorio principal de la segunda etapa
704[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
705
706#Localizar directorio segunda etapa del grub   
707PREFIXSECONDSTAGE="/boot/grubMBR"
708
709# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
710if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
711then
712    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
713    then
714        # Si no se reconfigura se utiliza el grub.cfg orginal
715        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
716                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
717        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
718        # Reactivamos el grub con el grub.cfg original.
719        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
720        return $?
721    fi
722fi
723
724# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
725#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
726echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
727echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
728
729#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
730[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
731
732#Preparar configuración segunda etapa: crear ubicacion
733mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
734#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
735sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
736/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
737#Preparar configuración segunda etapa: crear entrada del sistema operativo
738grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
739
740#Instalar el grub
741grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
742}
743
744
745
746#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
747#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
748#@param   int_disk_SecondStage     
749#@param   int_part_SecondStage     
750#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
751#@param   str "kernel param "   
752#@return 
753#@exception OG_ERR_FORMAT    Formato incorrecto.
754#@version 1.0.2 - Primeras pruebas.
755#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
756#@date    2011-10-29
757#@version 1.0.3 - Soporte para linux de 32 y 64 bits
758#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
759#@date    2012-03-13
760#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
761#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
762#@date    2012-03-13
763#*/ ##
764
765function ogGrubInstallPartition {
766
767# Variables locales.
768local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
769
770# Si se solicita, mostrar ayuda.
771if [ "$*" == "help" ]; then
772    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
773           "$FUNCNAME 1 1 FALSE " \
774           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
775    return
776fi 
777
778# Error si no se reciben 2 parámetros.
779[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
780
781DISK=$1; PART=$2;
782CHECKOS=${3:-"FALSE"}
783KERNELPARAM=$4
784BACKUPNAME=".backup.og"
785
786#error si no es linux.
787VERSION=$(ogGetOsVersion $DISK $PART)
788echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
789
790#Localizar primera etapa del grub
791FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
792
793#localizar disco segunda etapa del grub
794SECONDSTAGE=$(ogMount $DISK $PART)
795
796#Localizar directorio segunda etapa del grub   
797PREFIXSECONDSTAGE="/boot/grubPARTITION"
798
799# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
800if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
801then
802    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
803    then
804        # Si no se reconfigura se utiliza el grub.cfg orginal
805        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
806                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
807        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
808        # Reactivamos el grub con el grub.cfg original.
809        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
810        return $?
811    fi
812fi
813
814# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
815#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
816echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
817echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
818
819#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
820[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
821
822#Preparar configuración segunda etapa: crear ubicacion
823mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
824#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
825sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
826/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
827#Preparar configuración segunda etapa: crear entrada del sistema operativo
828grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
829
830#Instalar el grub
831grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
832}
833
834
835#/**
836#         ogConfigureFstab int_ndisk int_nfilesys
837#@brief   Configura el fstab según particiones existentes
838#@param   int_ndisk      nº de orden del disco
839#@param   int_nfilesys   nº de orden del sistema de archivos
840#@return  (nada)
841#@exception OG_ERR_FORMAT    Formato incorrecto.
842#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
843#@warning Puede haber un error si hay más de 1 partición swap.
844#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
845#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
846#@date    2013-03-21
847#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
848#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
849#@date    2016-11-03
850#*/ ##
851function ogConfigureFstab {
852# Variables locales.
853local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
854
855# Si se solicita, mostrar ayuda.
856if [ "$*" == "help" ]; then
857    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
858           "$FUNCNAME 1 1"
859    return
860fi
861# Error si no se reciben 2 parámetros.
862[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
863# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
864FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
865[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
866
867# Hacer copia de seguridad del fichero fstab original.
868cp -a ${FSTAB} ${FSTAB}.backup
869# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
870DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
871PARTROOT=$(ogDiskToDev $1 $2)
872# Configuración de swap (solo 1ª partición detectada).
873PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
874if [ -n "$PARTSWAP" ]
875then
876    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
877    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
878    if [ -n "$DEFSWAP" ]
879    then
880        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
881        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
882    else
883        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
884        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
885        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
886    fi 
887else
888    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
889    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
890fi
891}
892
893
894###
895#En pruebas
896##
897#/**
898#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
899#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
900#@param   int_ndisk      nº de orden del disco
901#@param   int_nfilesys   nº de orden del sistema de archivos
902#@param   str_name       nombre asignado (opcional)
903#@return  (nada)
904#@exception OG_ERR_FORMAT    Formato incorrecto.
905#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
906#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
907#@note    Si no se indica nombre, se asigna un valor por defecto.
908#@version 1.0.5 - Primera versión para OpenGnSys.
909#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
910#@date    2013-03-21
911#*/ ##
912function ogSetLinuxName ()
913{
914# Variables locales.
915local MNTDIR ETC NAME
916
917# Si se solicita, mostrar ayuda.
918if [ "$*" == "help" ]; then
919    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
920           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
921    return
922fi
923# Error si no se reciben 2 o 3 parámetros.
924case $# in
925    2)   # Asignar nombre automático (por defecto, "pc").
926         NAME="$(ogGetHostname)"
927         NAME=${NAME:-"pc"} ;;
928    3)   # Asignar nombre del 3er parámetro.
929         NAME="$3" ;;
930    *)   # Formato de ejecución incorrecto.
931         ogRaiseError $OG_ERR_FORMAT
932         return $?
933esac
934
935# Montar el sistema de archivos.
936MNTDIR=$(ogMount $1 $2) || return $?
937
938ETC=$(ogGetPath $1 $2 /etc)
939
940if [ -d "$ETC" ]; then
941        #cambio de nombre en hostname
942        echo "$NAME" > $ETC/hostname
943        #Opcion A para cambio de nombre en hosts
944        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
945        #Opcion B componer fichero de hosts
946        cat > $ETC/hosts <<EOF
947127.0.0.1       localhost
948127.0.1.1       $NAME
949
950# The following lines are desirable for IPv6 capable hosts
951::1     ip6-localhost ip6-loopback
952fe00::0 ip6-localnet
953ff00::0 ip6-mcastprefix
954ff02::1 ip6-allnodes
955ff02::2 ip6-allrouters
956EOF
957fi
958}
959
960
961
962#/**
963#         ogCleanLinuxDevices int_ndisk int_nfilesys
964#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
965#@param   int_ndisk      nº de orden del disco
966#@param   int_nfilesys   nº de orden del sistema de archivos
967#@return  (nada)
968#@exception OG_ERR_FORMAT    Formato incorrecto.
969#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
970#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
971#@version 1.0.5 - Primera versión para OpenGnSys.
972#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
973#@date    2013-03-21
974#@version 1.0.6b - Elimina fichero resume de hibernacion
975#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
976#@date    2016-11-07
977#*/ ##
978function ogCleanLinuxDevices ()
979{
980# Variables locales.
981local MNTDIR
982
983# Si se solicita, mostrar ayuda.
984if [ "$*" == "help" ]; then
985    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
986           "$FUNCNAME 1 1"
987    return
988fi
989# Error si no se reciben 2 parámetros.
990[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
991
992# Montar el sistema de archivos.
993MNTDIR=$(ogMount $1 $2) || return $?
994
995# Eliminar fichero de configuración de udev para dispositivos fijos de red.
996[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
997# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
998[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
999}
1000
1001#/**
1002# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
1003#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1004#@param 1 Numero de disco
1005#@param 2 Numero de particion
1006#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1007#@param 4 offline  configura el modo offline [offline|online] (opcional)
1008#@return  (nada)
1009#@exception OG_ERR_FORMAT    Formato incorrecto.
1010#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1011#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1012# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
1013#@version 1.0.6 - Prmera integración
1014#@author 
1015#@date    2016-11-07
1016#@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.
1017#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1018#@date    2017-06-17
1019#*/ ##
1020#*/ ##
1021
1022#*/
1023
1024function ogGrubAddOgLive () {
1025    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
1026
1027    # Si se solicita, mostrar ayuda.
1028    if [ "$*" == "help" ]; then
1029        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1030                "$FUNCNAME 1 1" \
1031                "$FUNCNAME 1 6 15 offline"
1032        return
1033    fi
1034
1035    # Error si no se reciben 2 parámetros.
1036    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
1037    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
1038
1039    # Error si no existe el kernel y el initrd en la cache.
1040    # Falta crear nuevo codigo de error.
1041    [ -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 $?)
1042
1043    # Archivo de configuracion del grub
1044    DIRMOUNT=$(ogMount $1 $2)
1045    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1046
1047    # Error si no existe archivo del grub
1048    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1049
1050    # Si existe la entrada de opengnsys, se borra
1051    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
1052
1053    # Tipo de tabla de particiones
1054    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1055
1056    # Localizacion de la cache
1057    read NUMDISK NUMPART <<< $(ogFindCache)
1058    let NUMDISK=$NUMDISK-1
1059    # kernel y sus opciones. Pasamos a modo usuario
1060    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
1061
1062    # Configuracion offline si existe parametro
1063    echo "$@" |grep offline &>/dev/null && STATUS=offline
1064    echo "$@" |grep online  &>/dev/null && STATUS=online
1065    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1066
1067    # Numero de línea de la primera entrada del grub.
1068    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1069    # Texto de la entrada de opengnsys
1070MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
1071\tinsmod part_$PARTTABLETYPE \n \
1072\tinsmod ext2 \n \
1073\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1074\tlinux $KERNEL \n \
1075\tinitrd /boot/${oglivedir}/oginitrd.img \n \
1076}"
1077
1078
1079    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1080    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1081
1082    # Ponemos que la entrada por defecto sea la primera.
1083    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1084
1085    # Si me dan valor para timeout lo cambio en el grub.
1086    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1087}
1088
1089#/**
1090# ogGrubHidePartitions num_disk num_part
1091#@see ogBootLoaderHidePartitions
1092#*/
1093function ogGrubHidePartitions {
1094    # Si se solicita, mostrar ayuda.
1095    if [ "$*" == "help" ]; then
1096        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1097               "$FUNCNAME 1 6"
1098        return
1099    fi
1100    ogBootLoaderHidePartitions $@
1101    return $?
1102}
1103
1104#/**
1105# ogBurgHidePartitions num_disk num_part
1106#@see ogBootLoaderHidePartitions
1107#*/
1108function ogBurgHidePartitions {
1109    # Si se solicita, mostrar ayuda.
1110    if [ "$*" == "help" ]; then
1111        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1112               "$FUNCNAME 1 6"
1113        return
1114    fi
1115    ogBootLoaderHidePartitions $@
1116    return $?
1117}
1118
1119#/**
1120# ogBootLoaderHidePartitions num_disk num_part
1121#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
1122#@param 1 Numero de disco
1123#@param 2 Numero de particion
1124#@return  (nada)
1125#@exception OG_ERR_FORMAT    Formato incorrecto.
1126#@exception No existe archivo de configuracion del grub/burg.
1127#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1128#@author  Irina Gomez, ETSII Universidad de Sevilla
1129#@date    2015-11-17
1130#@version 1.1 Se generaliza la función para grub y burg
1131#@author  Irina Gomez, ETSII Universidad de Sevilla
1132#@date    2017-10-20
1133#*/
1134function ogBootLoaderHidePartitions {
1135    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1136
1137    # Si se solicita, mostrar ayuda.
1138    if [ "$*" == "help" ]; then
1139        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
1140        return
1141    fi
1142
1143    # Nombre de la función que llama a esta.
1144    FUNC="${FUNCNAME[@]:1}"
1145    FUNC="${FUNC%%\ *}"
1146
1147    # Error si no se reciben 2 parámetros.
1148    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1149
1150    # Archivo de configuracion del grub
1151    DIRMOUNT=$(ogMount $1 $2)
1152    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1153    case "$FUNC" in
1154        ogGrubHidePartitions)
1155            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1156            ;;
1157        ogBurgHidePartitions)
1158            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1159            ;;
1160        *)
1161            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1162            return $?
1163            ;;
1164    esac
1165
1166    # Error si no existe archivo del grub
1167    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
1168
1169    # Si solo hay una particion de Windows me salgo
1170    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
1171
1172    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
1173    sed -i '/parttool/d' $CFGFILE
1174
1175    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1176
1177    # Entradas de Windows: numero de linea y particion. De mayor a menor.
1178    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
1179    # Particiones de Windows, pueden no estar en el grub.
1180    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
1181    # Modifico todas las entradas de Windows.
1182    for ENTRY in $WINENTRY; do
1183        LINE=${ENTRY%:*}
1184        PART=${ENTRY#*:}
1185        # En cada entrada, oculto o muestro cada particion.
1186        TEXT=""
1187        for PART2 in $WINPART; do
1188                # Muestro solo la particion de la entrada actual.
1189                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
1190
1191                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
1192        done
1193       
1194        sed -i "${LINE}a\ $TEXT" $CFGFILE
1195    done
1196
1197    # Activamos la particion que se inicia en todas las entradas de windows.
1198    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
1199
1200}
1201
1202#/**
1203# ogGrubDeleteEntry num_disk num_part num_part_delete
1204#@see ogBootLoaderDeleteEntry
1205#*/
1206function ogGrubDeleteEntry {
1207    # Si se solicita, mostrar ayuda.
1208    if [ "$*" == "help" ]; then
1209        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_npartition_delete" \
1210                "$FUNCNAME 1 6 2"
1211        return
1212    fi
1213    ogBootLoaderDeleteEntry $@
1214    return $?
1215}
1216
1217#/**
1218# ogBurgDeleteEntry num_disk num_part num_part_delete
1219#@see ogBootLoaderDeleteEntry
1220#*/
1221function ogBurgDeleteEntry {
1222    # Si se solicita, mostrar ayuda.
1223    if [ "$*" == "help" ]; then
1224        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_npartition_delete" \
1225                "$FUNCNAME 1 6 2"
1226        return
1227    fi
1228    ogBootLoaderDeleteEntry $@
1229    return $?
1230}
1231
1232#/**
1233# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1234#@brief Borra en el grub las entradas para el inicio en una particion.
1235#@param 1 Numero de disco donde esta el grub
1236#@param 2 Numero de particion donde esta el grub
1237#@param 3 Numero de la particion de la que borramos las entradas
1238#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
1239#@return  (nada)
1240#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1241#@exception OG_ERR_FORMAT    Formato incorrecto.
1242#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1243#@version 1.1 Se generaliza la función para grub y burg
1244#@author  Irina Gomez, ETSII Universidad de Sevilla
1245#@date    2017-10-20
1246#*/
1247function ogBootLoaderDeleteEntry {
1248    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
1249
1250    # Si se solicita, mostrar ayuda.
1251    if [ "$*" == "help" ]; then
1252        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1253        return
1254    fi
1255
1256    # Nombre de la función que llama a esta.
1257    FUNC="${FUNCNAME[@]:1}"
1258    FUNC="${FUNC%%\ *}"
1259
1260    # Archivo de configuracion del grub
1261    DIRMOUNT=$(ogMount $1 $2)
1262    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1263    case "$FUNC" in
1264        ogGrubDeleteEntry)
1265            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1266            ;;
1267        ogBurgDeleteEntry)
1268            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1269            ;;
1270        *)
1271            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1272            return $?
1273            ;;
1274    esac
1275
1276    # Error si no se reciben 3 parámetros.
1277    [ $# -lt 3 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNC num_disk num_part"; echo $?)
1278
1279    # Dispositivo
1280    DEVICE=$(ogDiskToDev $1)
1281
1282    # Error si no existe archivo del grub)
1283    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE"; echo $?)
1284
1285    # Numero de linea de cada entrada, de mayor a menor.
1286    MENUENTRY="$(grep -n -e menuentry.*$DEVICE $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1287
1288    # Entradas que hay que borrar.
1289    DELETEENTRY=$(grep -n menuentry.*$DEVICE$3 $CFGFILE| cut -d: -f1)
1290
1291    # Si no hay entradas para borrar me salgo con aviso
1292    [ "$DELETEENTRY" == "" ] && ogEcho session log warning "No menuentry $DEVICE$3" && return
1293
1294    # Recorremos el fichero del final hacia el principio.
1295    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1296    for ENTRY in $MENUENTRY; do
1297        # Comprobamos si hay que borrar la entrada.
1298        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1299            let ENDENTRY=$ENDENTRY-1
1300            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1301        fi
1302
1303        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1304        ENDENTRY=$ENTRY
1305    done
1306}
1307
1308
1309#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1310#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1311#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1312#@param   int_disk_SecondStage     
1313#@param   int_part_SecondStage     
1314#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1315#@return 
1316#@exception OG_ERR_FORMAT    Formato incorrecto.
1317#@exception OG_ERR_PARTITION  Partición no soportada
1318#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1319#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1320#@date    2017-06-23
1321#*/ ##
1322
1323function ogBurgInstallMbr {
1324 
1325# Variables locales.
1326local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1327
1328# Si se solicita, mostrar ayuda.
1329if [ "$*" == "help" ]; then
1330    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1331           "$FUNCNAME 1 1 FALSE " \
1332           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1333    return
1334fi 
1335
1336# Error si no se reciben 2 parametros.
1337[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1338
1339
1340DISK=$1; PART=$2;
1341CHECKOS=${3:-"FALSE"}
1342KERNELPARAM=$4
1343BACKUPNAME=".backup.og"
1344
1345#Error si no es linux.
1346ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1347
1348
1349#La primera etapa del grub se fija en el primer disco duro
1350FIRSTSTAGE=$(ogDiskToDev 1)
1351
1352#localizar disco segunda etapa del grub
1353SECONDSTAGE=$(ogMount $DISK $PART)
1354
1355# prepara el directorio principal de la segunda etapa (y copia los binarios)
1356[ -d ${SECONDSTAGE}/boot/burg/ ]  || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/*  ${SECONDSTAGE}/boot/burg/; cp  $OGLIB/burg/*  ${SECONDSTAGE}/boot/burg/;
1357
1358#Copiamos el tema
1359mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1360cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/"
1361
1362#Localizar directorio segunda etapa del grub   
1363#PREFIXSECONDSTAGE="/boot/burg/"
1364
1365# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1366if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1367then
1368    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1369    then
1370        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
1371        return $?
1372    fi
1373fi
1374
1375# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1376
1377#llamada a updateBootCache para que aloje la primera fase del ogLive
1378updateBootCache
1379
1380#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1381echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1382echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1383
1384
1385#Preparar configuración segunda etapa: crear ubicacion
1386mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1387
1388#Preparar configuración segunda etapa: crear cabecera del fichero
1389#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1390
1391FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1392
1393cat > "$FILECFG" << EOF
1394
1395set theme_name=OpenGnsys
1396set gfxmode=1024x768
1397#set root='(hd$(expr $DISK - 1),$(expr $PART - 1))'
1398
1399set locale_dir=(\$root)/boot/burg/locale
1400
1401#GRUB_DEFAULT="Reboot"
1402set default=0
1403set timeout=25
1404set lang=es
1405
1406
1407insmod ext2
1408insmod gettext
1409
1410
1411if [ -s \$prefix/burgenv ]; then
1412  load_env
1413fi
1414
1415if [ \${prev_saved_entry} ]; then
1416  set saved_entry=\${prev_saved_entry}
1417  save_env saved_entry
1418  set prev_saved_entry=
1419  save_env prev_saved_entry
1420  set boot_once=true
1421fi
1422
1423function savedefault {
1424  if [ -z \${boot_once} ]; then
1425    saved_entry=\${chosen}
1426    save_env saved_entry
1427  fi
1428}
1429function select_menu {
1430  if menu_popup -t template_popup theme_menu ; then
1431    free_config template_popup template_subitem menu class screen
1432    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1433    save_env theme_name
1434    menu_refresh
1435  fi
1436}
1437
1438function toggle_fold {
1439  if test -z $theme_fold ; then
1440    set theme_fold=1
1441  else
1442    set theme_fold=
1443  fi
1444  save_env theme_fold
1445  menu_refresh
1446}
1447function select_resolution {
1448  if menu_popup -t template_popup resolution_menu ; then
1449    menu_reload_mode
1450    save_env gfxmode
1451  fi
1452}
1453
1454
1455if test -f \${prefix}/themes/\${theme_name}/theme ; then
1456  insmod coreui
1457  menu_region.text
1458  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1459 # Comentar los hotkety
1460 #load_config \${prefix}/themes/conf.d/10_hotkey
1461  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1462  insmod vbe
1463  insmod png
1464  insmod jpeg
1465  set gfxfont="Unifont Regular 16"
1466  menu_region.gfx
1467  vmenu resolution_menu
1468  controller.ext
1469fi
1470
1471
1472EOF
1473
1474
1475#Preparar configuración segunda etapa: crear entrada del sistema operativo
1476grubSyntax "$KERNELPARAM" >> "$FILECFG"
1477
1478
1479#Instalar el burg
1480burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
1481}
1482
1483#/**
1484# ogBurgDefaultEntry   int_disk_GRUBCFG  int_partition_GRUBCFG
1485#@brief   Configura la entrada por defecto de Burg
1486#@param   int_disk_SecondStage     
1487#@param   int_part_SecondStage     
1488#@param   int_default_entry
1489#@return 
1490#@exception OG_ERR_FORMAT    Formato incorrecto.
1491#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1492#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1493#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1494#@version 1.1.0 - Primeras pruebas con Burg
1495#@author  Irina Gomez, ETSII Universidad de Sevilla
1496#@date    2017-08-09
1497#*/ ##
1498function ogBurgDefaultEntry {
1499
1500# Variables locales.
1501local PART BURGCFG
1502
1503# Si se solicita, mostrar ayuda.
1504if [ "$*" == "help" ]; then
1505    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_default_entry  " \
1506           "$FUNCNAME 1 1 0 "
1507    return
1508fi 
1509
1510# Error si no se reciben 3 parametros.
1511[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_default_entry" || return $?
1512
1513# Error si no puede montar sistema de archivos.
1514PART=$(ogMount $1 $2) || return $?
1515
1516# Comprobamos que $3 es un número
1517[[ $3 =~ ^[0-9]+$ ]] || ogRaiseError $OG_ERR_OUTOFLIMIT "\'$3\' not integer" ||  return $?
1518
1519# Comprobamos que exista fichero burg.cfg
1520BURGCFG=$PART/boot/burg/burg.cfg
1521[ -f $BURGCFG ] || ogRaiseError $OG_ERR_NOTFOUND "$BURGCFG" || return $?
1522
1523sed -i s/"^set default.*$"/"set default=$3"/g $BURGCFG
1524
1525echo "${MSG_HELP_ogBurgDefaultEntry%%\.}: $@"
1526}
1527
1528#/**
1529# ogBurgOgliveDefaultEntry
1530#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1531#@param   int_disk_SecondStage     
1532#@param   int_part_SecondStage     
1533#@return 
1534#@exception OG_ERR_FORMAT    Formato incorrecto.
1535#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1536#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1537#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1538#@version 1.1.0 - Primeras pruebas con Burg
1539#@author  Irina Gomez, ETSII Universidad de Sevilla
1540#@date    2017-08-09
1541#*/ ##
1542function  ogBurgOgliveDefaultEntry {
1543
1544# Variables locales.
1545local PART BURGCFG NUMENTRY
1546
1547# Si se solicita, mostrar ayuda.
1548if [ "$*" == "help" ]; then
1549    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" \
1550           "$FUNCNAME 1 1"
1551    return
1552fi 
1553
1554# Error si no se reciben 2 parametros.
1555[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1556
1557# Error si no puede montar sistema de archivos.
1558PART=$(ogMount $1 $2) || return $?
1559
1560# Comprobamos que exista fichero burg.cfg
1561BURGCFG=$PART/boot/burg/burg.cfg
1562[ -f $BURGCFG ] || ogRaiseError $OG_ERR_NOTFOUND "$BURGCFG" || return $?
1563
1564# Detectamos cual es la entrada de ogLive
1565NUMENTRY=$(grep ^menuentry $BURGCFG| grep -n "OpenGnsys Live"|cut -d: -f1)
1566
1567# Si no existe entrada de ogLive nos salimos
1568[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $BURGCFG" || return $?)
1569
1570let NUMENTRY=$NUMENTRY-1
1571sed -i s/"^set default.*$"/"set default=$NUMENTRY"/g $BURGCFG
1572
1573echo "${MSG_HELP_ogBurgOgliveDefaultEntry%\.}: $@"
1574}
1575
Note: See TracBrowser for help on using the repository browser.