source: client/engine/Boot.lib @ 744ecd6

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 744ecd6 was 2152c11f, checked in by irina <irinagomez@…>, 7 years ago

#811 ogBoot: Se usa setBootMode para el arranque de Windows con reinicio.

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

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