source: client/engine/Boot.lib @ d43640a

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

#827 ogGrubInstall configura entrada para el ogLive si existe partición cache

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

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