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

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 2f3d0532 was f2e6a2e, checked in by irina <irinagomez@…>, 7 years ago

#796 #791 ogGrubOgliveDefaultEntry: Se corrige errata que dejaba el fichero de configuración con un formato inválido

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

  • Property mode set to 100755
File size: 58.5 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#*/ ##
670
671function ogGrubInstallMbr {
672
673# Variables locales.
674local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
675
676# Si se solicita, mostrar ayuda.
677if [ "$*" == "help" ]; then
678    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
679           "$FUNCNAME 1 1 FALSE " \
680           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
681    return
682fi 
683
684# Error si no se reciben 2 parámetros.
685[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
686
687
688DISK=$1; PART=$2;
689CHECKOS=${3:-"FALSE"}
690KERNELPARAM=$4
691BACKUPNAME=".backup.og"
692
693#Error si no es linux.
694#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
695#VERSION=$(ogGetOsVersion $DISK $PART)
696#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
697
698#La primera etapa del grub se fija en el primer disco duro
699FIRSTSTAGE=$(ogDiskToDev 1)
700
701#localizar disco segunda etapa del grub
702SECONDSTAGE=$(ogMount $DISK $PART)
703
704# prepara el directorio principal de la segunda etapa
705[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
706
707#Localizar directorio segunda etapa del grub   
708PREFIXSECONDSTAGE="/boot/grubMBR"
709
710# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
711if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
712then
713    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
714    then
715        # Si no se reconfigura se utiliza el grub.cfg orginal
716        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
717                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
718        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
719        # Reactivamos el grub con el grub.cfg original.
720        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
721        return $?
722    fi
723fi
724
725# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
726#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
727echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
728echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
729
730#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
731[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
732
733#Preparar configuración segunda etapa: crear ubicacion
734mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
735#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
736sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
737/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
738#Preparar configuración segunda etapa: crear entrada del sistema operativo
739grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
740
741#Instalar el grub
742grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
743}
744
745
746
747#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
748#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
749#@param   int_disk_SecondStage     
750#@param   int_part_SecondStage     
751#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
752#@param   str "kernel param "   
753#@return 
754#@exception OG_ERR_FORMAT    Formato incorrecto.
755#@version 1.0.2 - Primeras pruebas.
756#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
757#@date    2011-10-29
758#@version 1.0.3 - Soporte para linux de 32 y 64 bits
759#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
760#@date    2012-03-13
761#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
762#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
763#@date    2012-03-13
764#*/ ##
765
766function ogGrubInstallPartition {
767
768# Variables locales.
769local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
770
771# Si se solicita, mostrar ayuda.
772if [ "$*" == "help" ]; then
773    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
774           "$FUNCNAME 1 1 FALSE " \
775           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
776    return
777fi 
778
779# Error si no se reciben 2 parámetros.
780[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
781
782DISK=$1; PART=$2;
783CHECKOS=${3:-"FALSE"}
784KERNELPARAM=$4
785BACKUPNAME=".backup.og"
786
787#error si no es linux.
788VERSION=$(ogGetOsVersion $DISK $PART)
789echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
790
791#Localizar primera etapa del grub
792FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
793
794#localizar disco segunda etapa del grub
795SECONDSTAGE=$(ogMount $DISK $PART)
796
797#Localizar directorio segunda etapa del grub   
798PREFIXSECONDSTAGE="/boot/grubPARTITION"
799
800# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
801if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
802then
803    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
804    then
805        # Si no se reconfigura se utiliza el grub.cfg orginal
806        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
807                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
808        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
809        # Reactivamos el grub con el grub.cfg original.
810        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
811        return $?
812    fi
813fi
814
815# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
816#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
817echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
818echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
819
820#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
821[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
822
823#Preparar configuración segunda etapa: crear ubicacion
824mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
825#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
826sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
827/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
828#Preparar configuración segunda etapa: crear entrada del sistema operativo
829grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
830
831#Instalar el grub
832grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
833}
834
835
836#/**
837#         ogConfigureFstab int_ndisk int_nfilesys
838#@brief   Configura el fstab según particiones existentes
839#@param   int_ndisk      nº de orden del disco
840#@param   int_nfilesys   nº de orden del sistema de archivos
841#@return  (nada)
842#@exception OG_ERR_FORMAT    Formato incorrecto.
843#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
844#@warning Puede haber un error si hay más de 1 partición swap.
845#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
846#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
847#@date    2013-03-21
848#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
849#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
850#@date    2016-11-03
851#*/ ##
852function ogConfigureFstab {
853# Variables locales.
854local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
855
856# Si se solicita, mostrar ayuda.
857if [ "$*" == "help" ]; then
858    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
859           "$FUNCNAME 1 1"
860    return
861fi
862# Error si no se reciben 2 parámetros.
863[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
864# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
865FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
866[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
867
868# Hacer copia de seguridad del fichero fstab original.
869cp -a ${FSTAB} ${FSTAB}.backup
870# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
871DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
872PARTROOT=$(ogDiskToDev $1 $2)
873# Configuración de swap (solo 1ª partición detectada).
874PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
875if [ -n "$PARTSWAP" ]
876then
877    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
878    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
879    if [ -n "$DEFSWAP" ]
880    then
881        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
882        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
883    else
884        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
885        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
886        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
887    fi 
888else
889    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
890    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
891fi
892}
893
894
895###
896#En pruebas
897##
898#/**
899#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
900#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
901#@param   int_ndisk      nº de orden del disco
902#@param   int_nfilesys   nº de orden del sistema de archivos
903#@param   str_name       nombre asignado (opcional)
904#@return  (nada)
905#@exception OG_ERR_FORMAT    Formato incorrecto.
906#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
907#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
908#@note    Si no se indica nombre, se asigna un valor por defecto.
909#@version 1.0.5 - Primera versión para OpenGnSys.
910#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
911#@date    2013-03-21
912#*/ ##
913function ogSetLinuxName ()
914{
915# Variables locales.
916local MNTDIR ETC NAME
917
918# Si se solicita, mostrar ayuda.
919if [ "$*" == "help" ]; then
920    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
921           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
922    return
923fi
924# Error si no se reciben 2 o 3 parámetros.
925case $# in
926    2)   # Asignar nombre automático (por defecto, "pc").
927         NAME="$(ogGetHostname)"
928         NAME=${NAME:-"pc"} ;;
929    3)   # Asignar nombre del 3er parámetro.
930         NAME="$3" ;;
931    *)   # Formato de ejecución incorrecto.
932         ogRaiseError $OG_ERR_FORMAT
933         return $?
934esac
935
936# Montar el sistema de archivos.
937MNTDIR=$(ogMount $1 $2) || return $?
938
939ETC=$(ogGetPath $1 $2 /etc)
940
941if [ -d "$ETC" ]; then
942        #cambio de nombre en hostname
943        echo "$NAME" > $ETC/hostname
944        #Opcion A para cambio de nombre en hosts
945        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
946        #Opcion B componer fichero de hosts
947        cat > $ETC/hosts <<EOF
948127.0.0.1       localhost
949127.0.1.1       $NAME
950
951# The following lines are desirable for IPv6 capable hosts
952::1     ip6-localhost ip6-loopback
953fe00::0 ip6-localnet
954ff00::0 ip6-mcastprefix
955ff02::1 ip6-allnodes
956ff02::2 ip6-allrouters
957EOF
958fi
959}
960
961
962
963#/**
964#         ogCleanLinuxDevices int_ndisk int_nfilesys
965#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
966#@param   int_ndisk      nº de orden del disco
967#@param   int_nfilesys   nº de orden del sistema de archivos
968#@return  (nada)
969#@exception OG_ERR_FORMAT    Formato incorrecto.
970#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
971#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
972#@version 1.0.5 - Primera versión para OpenGnSys.
973#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
974#@date    2013-03-21
975#@version 1.0.6b - Elimina fichero resume de hibernacion
976#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
977#@date    2016-11-07
978#*/ ##
979function ogCleanLinuxDevices ()
980{
981# Variables locales.
982local MNTDIR
983
984# Si se solicita, mostrar ayuda.
985if [ "$*" == "help" ]; then
986    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
987           "$FUNCNAME 1 1"
988    return
989fi
990# Error si no se reciben 2 parámetros.
991[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
992
993# Montar el sistema de archivos.
994MNTDIR=$(ogMount $1 $2) || return $?
995
996# Eliminar fichero de configuración de udev para dispositivos fijos de red.
997[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
998# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
999[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
1000}
1001
1002#/**
1003# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
1004#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1005#@param 1 Numero de disco
1006#@param 2 Numero de particion
1007#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1008#@param 4 offline  configura el modo offline [offline|online] (opcional)
1009#@return  (nada)
1010#@exception OG_ERR_FORMAT    Formato incorrecto.
1011#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1012#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1013# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
1014#@version 1.0.6 - Prmera integración
1015#@author 
1016#@date    2016-11-07
1017#@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.
1018#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1019#@date    2017-06-17
1020#*/ ##
1021#*/ ##
1022
1023#*/
1024
1025function ogGrubAddOgLive () {
1026    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
1027
1028    # Si se solicita, mostrar ayuda.
1029    if [ "$*" == "help" ]; then
1030        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1031                "$FUNCNAME 1 1" \
1032                "$FUNCNAME 1 6 15 offline"
1033        return
1034    fi
1035
1036    # Error si no se reciben 2 parámetros.
1037    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
1038    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
1039
1040    # Error si no existe el kernel y el initrd en la cache.
1041    # Falta crear nuevo codigo de error.
1042    [ -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 $?)
1043
1044    # Archivo de configuracion del grub
1045    DIRMOUNT=$(ogMount $1 $2)
1046    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1047
1048    # Error si no existe archivo del grub
1049    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1050
1051    # Si existe la entrada de opengnsys, se borra
1052    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
1053
1054    # Tipo de tabla de particiones
1055    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1056
1057    # Localizacion de la cache
1058    read NUMDISK NUMPART <<< $(ogFindCache)
1059    let NUMDISK=$NUMDISK-1
1060    # kernel y sus opciones. Pasamos a modo usuario
1061    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
1062
1063    # Configuracion offline si existe parametro
1064    echo "$@" |grep offline &>/dev/null && STATUS=offline
1065    echo "$@" |grep online  &>/dev/null && STATUS=online
1066    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1067
1068    # Numero de línea de la primera entrada del grub.
1069    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1070    # Texto de la entrada de opengnsys
1071MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
1072\tinsmod part_$PARTTABLETYPE \n \
1073\tinsmod ext2 \n \
1074\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1075\tlinux $KERNEL \n \
1076\tinitrd /boot/${oglivedir}/oginitrd.img \n \
1077}"
1078
1079
1080    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1081    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1082
1083    # Ponemos que la entrada por defecto sea la primera.
1084    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1085
1086    # Si me dan valor para timeout lo cambio en el grub.
1087    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1088}
1089
1090#/**
1091# ogGrubHidePartitions num_disk num_part
1092#@see ogBootLoaderHidePartitions
1093#*/
1094function ogGrubHidePartitions {
1095    # Si se solicita, mostrar ayuda.
1096    if [ "$*" == "help" ]; then
1097        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1098               "$FUNCNAME 1 6"
1099        return
1100    fi
1101    ogBootLoaderHidePartitions $@
1102    return $?
1103}
1104
1105#/**
1106# ogBurgHidePartitions num_disk num_part
1107#@see ogBootLoaderHidePartitions
1108#*/
1109function ogBurgHidePartitions {
1110    # Si se solicita, mostrar ayuda.
1111    if [ "$*" == "help" ]; then
1112        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1113               "$FUNCNAME 1 6"
1114        return
1115    fi
1116    ogBootLoaderHidePartitions $@
1117    return $?
1118}
1119
1120#/**
1121# ogBootLoaderHidePartitions num_disk num_part
1122#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
1123#@param 1 Numero de disco
1124#@param 2 Numero de particion
1125#@return  (nada)
1126#@exception OG_ERR_FORMAT    Formato incorrecto.
1127#@exception No existe archivo de configuracion del grub/burg.
1128#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1129#@author  Irina Gomez, ETSII Universidad de Sevilla
1130#@date    2015-11-17
1131#@version 1.1 Se generaliza la función para grub y burg
1132#@author  Irina Gomez, ETSII Universidad de Sevilla
1133#@date    2017-10-20
1134#*/
1135function ogBootLoaderHidePartitions {
1136    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1137
1138    # Si se solicita, mostrar ayuda.
1139    if [ "$*" == "help" ]; then
1140        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
1141        return
1142    fi
1143
1144    # Nombre de la función que llama a esta.
1145    FUNC="${FUNCNAME[@]:1}"
1146    FUNC="${FUNC%%\ *}"
1147
1148    # Error si no se reciben 2 parámetros.
1149    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1150
1151    # Archivo de configuracion del grub
1152    DIRMOUNT=$(ogMount $1 $2)
1153    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1154    case "$FUNC" in
1155        ogGrubHidePartitions)
1156            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1157            ;;
1158        ogBurgHidePartitions)
1159            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1160            ;;
1161        *)
1162            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1163            return $?
1164            ;;
1165    esac
1166
1167    # Error si no existe archivo del grub
1168    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
1169
1170    # Si solo hay una particion de Windows me salgo
1171    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
1172
1173    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
1174    sed -i '/parttool/d' $CFGFILE
1175
1176    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1177
1178    # Entradas de Windows: numero de linea y particion. De mayor a menor.
1179    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
1180    # Particiones de Windows, pueden no estar en el grub.
1181    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
1182    # Modifico todas las entradas de Windows.
1183    for ENTRY in $WINENTRY; do
1184        LINE=${ENTRY%:*}
1185        PART=${ENTRY#*:}
1186        # En cada entrada, oculto o muestro cada particion.
1187        TEXT=""
1188        for PART2 in $WINPART; do
1189                # Muestro solo la particion de la entrada actual.
1190                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
1191
1192                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
1193        done
1194       
1195        sed -i "${LINE}a\ $TEXT" $CFGFILE
1196    done
1197
1198    # Activamos la particion que se inicia en todas las entradas de windows.
1199    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
1200
1201}
1202
1203#/**
1204# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
1205#@see ogBootLoaderDeleteEntry
1206#*/
1207function ogGrubDeleteEntry {
1208    # Si se solicita, mostrar ayuda.
1209    if [ "$*" == "help" ]; then
1210        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1211                "$FUNCNAME 1 6 2 1"
1212        return
1213    fi
1214    ogBootLoaderDeleteEntry $@
1215    return $?
1216}
1217
1218#/**
1219# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
1220#@see ogBootLoaderDeleteEntry
1221#*/
1222function ogBurgDeleteEntry {
1223    # Si se solicita, mostrar ayuda.
1224    if [ "$*" == "help" ]; then
1225        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1226                "$FUNCNAME 1 6 2 1"
1227        return
1228    fi
1229    ogBootLoaderDeleteEntry $@
1230    return $?
1231}
1232
1233#/**
1234# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
1235#@brief Borra en el grub las entradas para el inicio en una particion.
1236#@param 1 Numero de disco donde esta el grub
1237#@param 2 Numero de particion donde esta el grub
1238#@param 3 Numero del disco del que borramos las entradas
1239#@param 4 Numero de la particion de la que borramos las entradas
1240#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
1241#@return  (nada)
1242#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
1243#@exception OG_ERR_FORMAT    Formato incorrecto.
1244#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1245#@version 1.1 Se generaliza la función para grub y burg
1246#@author  Irina Gomez, ETSII Universidad de Sevilla
1247#@date    2017-10-20
1248#*/
1249function ogBootLoaderDeleteEntry {
1250    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
1251
1252    # Si se solicita, mostrar ayuda.
1253    if [ "$*" == "help" ]; then
1254        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1255        return
1256    fi
1257
1258    # Si el número de parámetros menos que 4 nos salimos
1259    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1260 
1261
1262    # Nombre de la función que llama a esta.
1263    FUNC="${FUNCNAME[@]:1}"
1264    FUNC="${FUNC%%\ *}"
1265
1266    # Archivo de configuracion del grub
1267    DIRMOUNT=$(ogMount $1 $2)
1268    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1269    case "$FUNC" in
1270        ogGrubDeleteEntry)
1271            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1272            ;;
1273        ogBurgDeleteEntry)
1274            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1275            ;;
1276        *)
1277            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1278            return $?
1279            ;;
1280    esac
1281
1282    # Dispositivo
1283    DEVICE=$(ogDiskToDev $3 $4)
1284
1285    # Error si no existe archivo del grub)
1286    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
1287
1288    # Numero de linea de cada entrada.
1289    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
1290
1291    # Entradas que hay que borrar.
1292    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1293
1294    # Si no hay entradas para borrar me salgo con aviso
1295    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
1296
1297    # Recorremos el fichero del final hacia el principio.
1298    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
1299    for ENTRY in $MENUENTRY; do
1300        # Comprobamos si hay que borrar la entrada.
1301        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1302            let ENDENTRY=$ENDENTRY-1
1303            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
1304        fi
1305
1306        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1307        ENDENTRY=$ENTRY
1308    done
1309}
1310
1311
1312#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1313#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1314#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1315#@param   int_disk_SecondStage     
1316#@param   int_part_SecondStage     
1317#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1318#@return 
1319#@exception OG_ERR_FORMAT    Formato incorrecto.
1320#@exception OG_ERR_PARTITION  Partición no soportada
1321#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1322#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1323#@date    2017-06-23
1324#*/ ##
1325
1326function ogBurgInstallMbr {
1327 
1328# Variables locales.
1329local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1330
1331# Si se solicita, mostrar ayuda.
1332if [ "$*" == "help" ]; then
1333    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1334           "$FUNCNAME 1 1 FALSE " \
1335           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1336    return
1337fi 
1338
1339# Error si no se reciben 2 parametros.
1340[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1341
1342
1343DISK=$1; PART=$2;
1344CHECKOS=${3:-"FALSE"}
1345KERNELPARAM=$4
1346BACKUPNAME=".backup.og"
1347
1348#Error si no es linux.
1349ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1350
1351
1352#La primera etapa del grub se fija en el primer disco duro
1353FIRSTSTAGE=$(ogDiskToDev 1)
1354
1355#localizar disco segunda etapa del grub
1356SECONDSTAGE=$(ogMount $DISK $PART)
1357
1358# prepara el directorio principal de la segunda etapa (y copia los binarios)
1359[ -d ${SECONDSTAGE}/boot/burg/ ]  || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/*  ${SECONDSTAGE}/boot/burg/; cp  $OGLIB/burg/*  ${SECONDSTAGE}/boot/burg/;
1360
1361#Copiamos el tema
1362mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
1363cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/"
1364
1365#Localizar directorio segunda etapa del grub   
1366#PREFIXSECONDSTAGE="/boot/burg/"
1367
1368# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1369if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1370then
1371    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1372    then
1373        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
1374        return $?
1375    fi
1376fi
1377
1378# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1379
1380#llamada a updateBootCache para que aloje la primera fase del ogLive
1381updateBootCache
1382
1383#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1384echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1385echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1386
1387
1388#Preparar configuración segunda etapa: crear ubicacion
1389mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1390
1391#Preparar configuración segunda etapa: crear cabecera del fichero
1392#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1393
1394FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1395
1396cat > "$FILECFG" << EOF
1397
1398set theme_name=OpenGnsys
1399set gfxmode=1024x768
1400#set root='(hd$(expr $DISK - 1),$(expr $PART - 1))'
1401
1402set locale_dir=(\$root)/boot/burg/locale
1403
1404#GRUB_DEFAULT="Reboot"
1405set default=0
1406set timeout=25
1407set lang=es
1408
1409
1410insmod ext2
1411insmod gettext
1412
1413
1414if [ -s \$prefix/burgenv ]; then
1415  load_env
1416fi
1417
1418if [ \${prev_saved_entry} ]; then
1419  set saved_entry=\${prev_saved_entry}
1420  save_env saved_entry
1421  set prev_saved_entry=
1422  save_env prev_saved_entry
1423  set boot_once=true
1424fi
1425
1426function savedefault {
1427  if [ -z \${boot_once} ]; then
1428    saved_entry=\${chosen}
1429    save_env saved_entry
1430  fi
1431}
1432function select_menu {
1433  if menu_popup -t template_popup theme_menu ; then
1434    free_config template_popup template_subitem menu class screen
1435    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1436    save_env theme_name
1437    menu_refresh
1438  fi
1439}
1440
1441function toggle_fold {
1442  if test -z $theme_fold ; then
1443    set theme_fold=1
1444  else
1445    set theme_fold=
1446  fi
1447  save_env theme_fold
1448  menu_refresh
1449}
1450function select_resolution {
1451  if menu_popup -t template_popup resolution_menu ; then
1452    menu_reload_mode
1453    save_env gfxmode
1454  fi
1455}
1456
1457
1458if test -f \${prefix}/themes/\${theme_name}/theme ; then
1459  insmod coreui
1460  menu_region.text
1461  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
1462 # Comentar los hotkety
1463 #load_config \${prefix}/themes/conf.d/10_hotkey
1464  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1465  insmod vbe
1466  insmod png
1467  insmod jpeg
1468  set gfxfont="Unifont Regular 16"
1469  menu_region.gfx
1470  vmenu resolution_menu
1471  controller.ext
1472fi
1473
1474
1475EOF
1476
1477
1478#Preparar configuración segunda etapa: crear entrada del sistema operativo
1479grubSyntax "$KERNELPARAM" >> "$FILECFG"
1480
1481
1482#Instalar el burg
1483burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
1484}
1485
1486#/**
1487# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
1488#@see ogBootLoaderDefaultEntry
1489#*/
1490function ogGrubDefaultEntry {
1491    # Si se solicita, mostrar ayuda.
1492    if [ "$*" == "help" ]; then
1493        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1494               "$FUNCNAME 1 6 1 1"
1495        return
1496    fi
1497    ogBootLoaderDefaultEntry $@
1498    return $?
1499}
1500
1501#/**
1502# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
1503#@see ogBootLoaderDefaultEntry
1504#*/
1505function ogBurgDefaultEntry {
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# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
1518#@brief   Configura la entrada por defecto de Burg
1519#@param   int_disk_SecondStage     
1520#@param   int_part_SecondStage     
1521#@param   int_disk_default_entry
1522#@param   int_part_default_entry
1523#@return 
1524#@exception OG_ERR_FORMAT    Formato incorrecto.
1525#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1526#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1527#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
1528#@version 1.1.0 - Define la entrada por defecto del Burg
1529#@author  Irina Gomez, ETSII Universidad de Sevilla
1530#@date    2017-08-09
1531#@version 1.1 Se generaliza la función para grub y burg
1532#@author  Irina Gomez, ETSII Universidad de Sevilla
1533#@date    2018-01-04
1534#*/ ##
1535function ogBootLoaderDefaultEntry {
1536
1537# Variables locales.
1538local PART CFGFILE DEFAULTENTRY MSG
1539
1540# Si se solicita, mostrar ayuda.
1541if [ "$*" == "help" ]; then
1542    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
1543    return
1544fi 
1545
1546# Nombre de la función que llama a esta.
1547FUNC="${FUNCNAME[@]:1}"
1548FUNC="${FUNC%%\ *}"
1549
1550# Error si no se reciben 3 parametros.
1551[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
1552
1553# Error si no puede montar sistema de archivos.
1554DIRMOUNT=$(ogMount $1 $2) || return $?
1555
1556# Comprobamos que exista fichero de configuración
1557# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1558case "$FUNC" in
1559    ogGrubDefaultEntry)
1560        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1561        ;;
1562    ogBurgDefaultEntry)
1563        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1564        ;;
1565    *)
1566        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1567        return $?
1568        ;;
1569esac
1570
1571# Error si no existe archivo de configuración
1572[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1573
1574# Dispositivo
1575DEVICE=$(ogDiskToDev $3 $4)
1576
1577# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1578DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
1579
1580# Si no hay entradas para borrar me salgo con aviso
1581[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
1582
1583# Número de la de linea por defecto en el menú de usuario
1584MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1585# Las líneas empiezan a contar desde cero
1586let MENUENTRY=$MENUENTRY-1
1587
1588sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1589
1590MSG="MSG_HELP_$FUNC"
1591echo "${!MSG%%\.}: $@"
1592}
1593
1594#/**
1595# ogGrubOgliveDefaultEntry num_disk num_part
1596#@see ogBootLoaderOgliveDefaultEntry
1597#*/
1598function ogGrubOgliveDefaultEntry {
1599    # Si se solicita, mostrar ayuda.
1600    if [ "$*" == "help" ]; then
1601        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1602               "$FUNCNAME 1 6"
1603        return
1604    fi
1605    ogBootLoaderOgliveDefaultEntry $@
1606    return $?
1607}
1608
1609#/**
1610# ogBurgOgliveDefaultEntry num_disk num_part
1611#@see ogBootLoaderOgliveDefaultEntry
1612#*/
1613function ogBurgOgliveDefaultEntry {
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# ogBootLoaderOgliveDefaultEntry
1626#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1627#@param   int_disk_SecondStage     
1628#@param   int_part_SecondStage     
1629#@return 
1630#@exception OG_ERR_FORMAT    Formato incorrecto.
1631#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1632#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1633#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1634#@version 1.1.0 - Primeras pruebas con Burg
1635#@author  Irina Gomez, ETSII Universidad de Sevilla
1636#@date    2017-08-09
1637#@version 1.1 Se generaliza la función para grub y burg
1638#@author  Irina Gomez, ETSII Universidad de Sevilla
1639#@date    2018-01-04
1640#*/ ##
1641function  ogBootLoaderOgliveDefaultEntry {
1642
1643# Variables locales.
1644local FUNC PART CFGFILE NUMENTRY MSG
1645
1646# Si se solicita, mostrar ayuda.
1647if [ "$*" == "help" ]; then
1648    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
1649    return
1650fi 
1651
1652# Nombre de la función que llama a esta.
1653FUNC="${FUNCNAME[@]:1}"
1654FUNC="${FUNC%%\ *}"
1655
1656# Error si no se reciben 2 parametros.
1657[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1658
1659# Error si no puede montar sistema de archivos.
1660PART=$(ogMount $1 $2) || return $?
1661# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1662case "$FUNC" in
1663    ogGrubOgliveDefaultEntry)
1664        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1665        ;;
1666    ogBurgOgliveDefaultEntry)
1667        CFGFILE="$PART/boot/burg/burg.cfg"
1668        ;;
1669    *)
1670        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1671        return $?
1672        ;;
1673esac
1674
1675# Comprobamos que exista fichero de configuración
1676[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1677
1678# Detectamos cual es la entrada de ogLive
1679NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
1680
1681# Si no existe entrada de ogLive nos salimos
1682[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
1683
1684let NUMENTRY=$NUMENTRY-1
1685sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
1686
1687MSG="MSG_HELP_$FUNC"
1688echo "${!MSG%%\.}: $@"
1689}
1690
Note: See TracBrowser for help on using the repository browser.