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
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.
[16360e4]23#@note    En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB.
[f5432db7]24#@note    En Linux, debe arrancarse la partición del directorio \c /boot
[3915005]25#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib 
[985bef0]26#@author  Antonio J. Doblas Viso, Universidad de Malaga
[e05993a]27#@date    2008-10-27
[3915005]28#@version 0.9 - Adaptación para OpenGnSys.
[b094c59]29#@author  Ramon Gomez, ETSII Universidad de Sevilla
30#@date    2009-09-11
[40ad2e8d]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
[8fc2631]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.
[2b2f533]35#@author  Ramon Gomez, ETSII Universidad de Sevilla
[8fc2631]36#@date    2015-06-05
[16360e4]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
[1e7eaab]40#*/ ##
[42669ebf]41function ogBoot ()
42{
[b094c59]43# Variables locales.
[40ad2e8d]44local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
[b094c59]45
[1e7eaab]46# Si se solicita, mostrar ayuda.
[b094c59]47if [ "$*" == "help" ]; then
[dc4eac6]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\""
[b094c59]50    return
51fi
[16360e4]52# Error si no se reciben 2 o 3 parámetros.
53[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b094c59]54
[1e7eaab]55# Detectar tipo de sistema de archivos y montarlo.
[049eadbe]56PART=$(ogDiskToDev $1 $2) || return $?
[2b2f533]57TYPE=$(ogGetOsType $1 $2) || return $?
[a73649d]58# Error si no puede montar sistema de archivos.
[5962edd]59MNTDIR=$(ogMount $1 $2) || return $?
[b094c59]60
61case "$TYPE" in
[2b2f533]62    Linux|Android)
[16360e4]63        # Si no se indican, obtiene los parámetros de arranque para Linux.
[da82642]64        PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}"
[21815bd5]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.
[da82642]68            PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
[8fc2631]69            # Montar S.F. de /boot.
70            MNTDIR=$(ogMount $PART) || return $?
[21815bd5]71            # Buscar los datos de arranque.
72            PARAMS=$(ogLinuxBootParameters $PART) || exit $?
73        fi
[f5432db7]74        read -e KERNEL INITRD APPEND <<<"$PARAMS"
[1e7eaab]75        # Si no hay kernel, no hay sistema operativo.
[045fd2d]76        [ -n "$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
[1e7eaab]77        # Arrancar de partición distinta a la original.
[049eadbe]78        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
[f5432db7]79        # Configurar kernel Linux con los parámetros leídos de su GRUB.
[049eadbe]80        kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
[40ad2e8d]81        kexec -e &
[f5432db7]82        ;;
[477ba42]83    Windows|WinLoader)
[1e7eaab]84        # Compruebar si hay un cargador de Windows.
[f5432db7]85        for f in io.sys ntldr bootmgr; do
86            FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
[d10549b]87            [ -n "$FILE" ] && LOADER="$f"
[f5432db7]88        done
[045fd2d]89        [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
[40ad2e8d]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).
[fc65d8d9]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
[4085f13]104            # Activar la partición.
105            ogSetPartitionActive $1 $2
[75a296b]106            reboot
107        fi
[f5432db7]108        ;;
[2b2f533]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        ;;
[477ba42]119    *)  ogRaiseError $OG_ERR_NOTOS "$1 $2 ${TYPE:+($TYPE)}"
[326cec3]120        return $?
[f5432db7]121        ;;
[b094c59]122esac
123}
124
125
126#/**
[16360e4]127#         ogGetWindowsName int_ndisk int_nfilesys
[3e1561d]128#@brief   Muestra el nombre del equipo en el registro de Windows.
[42669ebf]129#@param   int_ndisk      nº de orden del disco
[16360e4]130#@param   int_nfilesys   nº de orden del sistema de archivos
[3e1561d]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.
[3915005]135#@version 0.9 - Adaptación para OpenGnSys.
[3e1561d]136#@author  Ramon Gomez, ETSII Universidad de Sevilla
137#@date    2009-09-23
[1e7eaab]138#*/ ##
[42669ebf]139function ogGetWindowsName ()
140{
[3e1561d]141# Variables locales.
142local PART MNTDIR
143
[1e7eaab]144# Si se solicita, mostrar ayuda.
[3e1561d]145if [ "$*" == "help" ]; then
146    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
147           "$FUNCNAME 1 1  ==>  PRACTICA-PC"
148    return
149fi
[1e7eaab]150# Error si no se reciben 2 parámetros.
[3e1561d]151[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
152
[1e7eaab]153# Montar el sistema de archivos.
[5962edd]154MNTDIR=$(ogMount $1 $2) || return $?
[3e1561d]155
[1e7eaab]156# Obtener dato del valor de registro.
[3e1561d]157ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
158}
159
160
161#/**
[b94c497]162#         ogLinuxBootParameters int_ndisk int_nfilesys
[b094c59]163#@brief   Muestra los parámetros de arranque de un sistema de archivos Linux.
[42669ebf]164#@param   int_ndisk      nº de orden del disco
[b94c497]165#@param   int_nfilesys   nº de orden del sistema de archivos
[42669ebf]166#@return  str_kernel str_initrd str_parameters ...
[b094c59]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.
[055adcf]170#@warning Función básica usada por \c ogBoot
[3915005]171#@version 0.9 - Primera adaptación para OpenGnSys.
[b094c59]172#@author  Ramon Gomez, ETSII Universidad de Sevilla
173#@date    2009-09-11
[199bdf3]174#@version 0.9.2 - Soporta partición /boot independiente.
175#@author  Ramon Gomez, ETSII Universidad de Sevilla
176#@date    2010-07-20
[b94c497]177#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
178#@author  Ramon Gomez, ETSII Universidad de Sevilla
179#@date    2013-05-14
[6647a20]180#@version 1.0.6 - Detectar instalaciones sobre EFI.
181#@author  Ramon Gomez, ETSII Universidad de Sevilla
182#@date    2014-09-15
[1e7eaab]183#*/ ##
[42669ebf]184function ogLinuxBootParameters ()
185{
[b094c59]186# Variables locales.
[6647a20]187local MNTDIR CONFDIR CONFFILE f
[b094c59]188
[1e7eaab]189# Si se solicita, mostrar ayuda.
[b094c59]190if [ "$*" == "help" ]; then
[b94c497]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"
[b094c59]193    return
194fi
[1e7eaab]195# Error si no se reciben 2 parámetros.
[b094c59]196[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
197
[1e7eaab]198# Detectar id. de tipo de partición y codificar al mnemonico.
[5962edd]199MNTDIR=$(ogMount $1 $2) || return $?
[b094c59]200
201# Fichero de configuración de GRUB.
[6647a20]202CONFDIR=$MNTDIR                               # Sistema de archivos de arranque (/boot).
203[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot   # Sist. archivos raíz con directorio boot.
[d7ffbfc]204for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
[6647a20]205    [ -r $f ] && CONFFILE=$f
206done
[cf8a0ae]207[ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
[b094c59]208
[1e7eaab]209# Toma del fichero de configuracion los valores del kernel, initrd
[ee4a96e]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 .  */
[1e7eaab]213# /* (comentario Doxygen)
[b094c59]214awk 'BEGIN {cont=-1;}
[b94c497]215     $1~/^default$/     {sub(/=/," "); def=$2;}
[6647a20]216     $1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3;
[b94c497]217                                   if (def ~ /saved_entry/) def=0;
[6647a20]218                                 }
[b94c497]219     $1~/^(title|menuentry)$/ {cont++}
[529c585]220     $1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; }
[8fc2631]221     $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
[6647a20]222                                       kern=$2;
223                                       sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
[8fc2631]224                                      } # /* (comentario Doxygen)
225                                    }
226     $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
[b094c59]227     END {if (kern!="") printf("%s %s %s", kern,init,app)}
[199bdf3]228    ' $CONFFILE
[1e7eaab]229# */ (comentario Doxygen)
[b094c59]230}
231
[3e1561d]232
233#/**
[e538e62]234#         ogSetWindowsName int_ndisk int_nfilesys str_name
[3e1561d]235#@brief   Establece el nombre del equipo en el registro de Windows.
[42669ebf]236#@param   int_ndisk      nº de orden del disco
[e538e62]237#@param   int_nfilesys   nº de orden del sistema de archivos
[42669ebf]238#@param   str_name       nombre asignado
[3e1561d]239#@return  (nada)
[e538e62]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.
[3915005]244#@version 0.9 - Adaptación a OpenGnSys.
[3e1561d]245#@author  Ramon Gomez, ETSII Universidad de Sevilla
246#@date    2009-09-24
[e538e62]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
[1e7eaab]250#*/ ##
[42669ebf]251function ogSetWindowsName ()
252{
[3e1561d]253# Variables locales.
254local PART MNTDIR NAME
255
[1e7eaab]256# Si se solicita, mostrar ayuda.
[3e1561d]257if [ "$*" == "help" ]; then
[e538e62]258    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
[3e1561d]259           "$FUNCNAME 1 1 PRACTICA-PC"
260    return
261fi
[1e7eaab]262# Error si no se reciben 3 parámetros.
[3e1561d]263[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[e538e62]264# Error si el nombre supera los 15 caracteres.
265[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
[3e1561d]266
[42669ebf]267# Montar el sistema de archivos.
[5962edd]268MNTDIR=$(ogMount $1 $2) || return $?
269
270# Asignar nombre.
[3e1561d]271NAME="$3"
272
[1e7eaab]273# Modificar datos de los valores de registro.
[4b9cdda]274ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
275ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
[42e8020]276ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\HostName' "$NAME" 2>/dev/null
[4b9cdda]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
[42e8020]279ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV HostName' "$NAME" 2>/dev/null
[4b9cdda]280ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
[3e1561d]281}
282
[f5432db7]283
[4b9cdda]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.
[3915005]294#@version 0.9.2 - Adaptación a OpenGnSys.
[4b9cdda]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.
[5962edd]313MNTDIR=$(ogMount $1 $2) || return $?
314
315# Asignar nombre.
[4b9cdda]316NAME="$3"
317
318# Modificar datos en el registro.
319ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
320}
321
[38231e9]322
323#/**
[9e8773c]324#         ogBootMbrXP int_ndisk
[38231e9]325#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
[42669ebf]326#@param   int_ndisk      nº de orden del disco
[945b003]327#@return  salida del programa my-sys
[38231e9]328#@exception OG_ERR_FORMAT    Formato incorrecto.
329#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]330#@version 0.9 - Adaptación a OpenGnSys.
[38231e9]331#@author  Antonio J. Doblas Viso. Universidad de Málaga
332#@date    2009-09-24
333#*/ ##
334
[9e8773c]335function ogBootMbrXP ()
[e05993a]336{
[38231e9]337# Variables locales.
[a73649d]338local DISK
[38231e9]339
340# Si se solicita, mostrar ayuda.
341if [ "$*" == "help" ]; then
342    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
[a73649d]343           "$FUNCNAME 1"
[38231e9]344    return
[945b003]345fi
[a73649d]346# Error si no se recibe 1 parámetro.
[38231e9]347[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
348
[a73649d]349DISK="$(ogDiskToDev $1)" || return $?
350ms-sys -z -f $DISK
351ms-sys -m -f $DISK
[945b003]352}
[42669ebf]353
[fdad5a6]354
[9e8773c]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.
[3915005]362#@version 0.9 - Adaptación a OpenGnSys.
[9e8773c]363#@author  Antonio J. Doblas Viso. Universidad de Málaga
364#@date    2009-09-24
365#*/ ##
366
367function ogBootMbrGeneric ()
368{
369# Variables locales.
[a73649d]370local DISK
[9e8773c]371
372# Si se solicita, mostrar ayuda.
373if [ "$*" == "help" ]; then
374    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
375           "$FUNCNAME 1 "
376    return
377fi
[a73649d]378# Error si no se recibe 1 parámetro.
[9e8773c]379[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
380
[a73649d]381DISK="$(ogDiskToDev $1)" || return $?
382ms-sys -z -f $DISK
383ms-sys -s -f $DISK
[9e8773c]384}
385
386
387
[fdad5a6]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.
[3915005]397#@version 0.9 - Adaptación a OpenGnSys.
[fdad5a6]398#@author  Antonio J. Doblas Viso. Universidad de Málaga
399#@date    2009-09-24
400#*/ ##
401
402function ogFixBootSector ()
403{
404# Variables locales.
[1cd64e6]405local PARTYPE DISK PART FILE
[fdad5a6]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)
[3915005]420case "$PARTYPE" in
[0a7f5c9]421        1|4|6|7|b|c|e|f|17|700)
[fdad5a6]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
[1cd64e6]433FILE=/tmp/temp$$
[fdad5a6]434cat > $FILE <<EOF
435disk=$DISK
436main_part=$PART
437fix_first_sector=yes
438EOF
439
[5fde4bc]440spartlnx.run -cui -nm -a -f $FILE &
441sleep 5
442ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
[1cd64e6]443rm -f $FILE
[fdad5a6]444}
445
446
447
448#/**
449#         ogWindowsBootParameters int_ndisk int_parition
[78b5dfe7]450#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
[fdad5a6]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.
[3915005]456#@version 0.9 - Integración desde EAC para OpenGnSys.
[fdad5a6]457#@author  Antonio J. Doblas Viso. Universidad de Málaga
458#@date    2009-09-24
[78b5dfe7]459#@version 1.0.1 - Adapatacion para OpenGnsys.
460#@author  Antonio J. Doblas Viso. Universidad de Málaga
461#@date    2011-05-20
[e763190]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
[b6971f1]465#@version 1.1.0 - Soporte para Windows 10.
466#@author  Ramon Gomez, ETSII Universidad de Sevilla
467#@date    2016-01-19
[fdad5a6]468#*/ ##
469
470function ogWindowsBootParameters ()
471{
472# Variables locales.
[ccf1fa0]473local PART DISK FILE WINVER MOUNT
[fdad5a6]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
[e763190]487#Preparando variables adaptadas a sintaxis windows.
488let DISK=$1-1
489PART=$2
490FILE=/tmp/temp$$
491
[ccf1fa0]492# Obtener versión de Windows.
[1e4000f]493WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
[ccf1fa0]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
[fdad5a6]502fi
503
504ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
[78b5dfe7]505
[fdad5a6]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
[5fde4bc]515spartlnx.run -cui -nm -w -f $FILE &
516sleep 5
517ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
518
519 
[fdad5a6]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
[5fde4bc]529spartlnx.run -cui -nm -w -f $FILE &
530sleep 5
531ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
532
[fdad5a6]533
[250742d]534##Preparando instruccion        Ramdisk Options
[5fde4bc]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
[fdad5a6]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
[5fde4bc]555spartlnx.run -cui -nm -w -f $FILE &
556sleep 5
557ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
558
[fdad5a6]559
560#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
[5fde4bc]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
[fdad5a6]571
572}
[3915005]573
[fdad5a6]574
[78b5dfe7]575#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
[fdad5a6]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.
[3915005]585#@version 0.9 - Adaptación a OpenGnSys.
[fdad5a6]586#@author  Antonio J. Doblas Viso. Universidad de Málaga
587#@date    2009-09-24
588#*/ ##
[78b5dfe7]589function ogWindowsRegisterPartition ()
[3915005]590{
[fdad5a6]591# Variables locales.
[3915005]592local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
[fdad5a6]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
[3915005]609FILE=/tmp/temp$$
[fdad5a6]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
[5fde4bc]643spartlnx.run -cui -nm -u -f $FILE &
644sleep 5
645ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
646
[e0c0d93]647}
[ab82469]648
649
[59c5b66]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.
[9c535e0]652#@param   int_disk_SecondStage     
653#@param   int_part_SecondStage     
654#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
[ab82469]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
[9c535e0]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
[59c5b66]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
[59cebeed]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
[ab82469]672#*/ ##
673
[9c535e0]674function ogGrubInstallMbr {
[ab82469]675
676# Variables locales.
[1c69be8]677local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[ab82469]678
679# Si se solicita, mostrar ayuda.
680if [ "$*" == "help" ]; then
[9c535e0]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 \" "
[ab82469]684    return
[9c535e0]685fi 
[ab82469]686
687# Error si no se reciben 2 parámetros.
[9c535e0]688[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
[ab82469]689
690
[9c535e0]691DISK=$1; PART=$2;
692CHECKOS=${3:-"FALSE"}
693KERNELPARAM=$4
[1c69be8]694BACKUPNAME=".backup.og"
[ab82469]695
[9c535e0]696#Error si no es linux.
697#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
[a4b1e2a]698#VERSION=$(ogGetOsVersion $DISK $PART)
699#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
[ab82469]700
[59c5b66]701#La primera etapa del grub se fija en el primer disco duro
702FIRSTSTAGE=$(ogDiskToDev 1)
[ab82469]703
[9c535e0]704#localizar disco segunda etapa del grub
705SECONDSTAGE=$(ogMount $DISK $PART)
[ab82469]706
[a4b1e2a]707# prepara el directorio principal de la segunda etapa
708[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
709
[9c535e0]710#Localizar directorio segunda etapa del grub   
711PREFIXSECONDSTAGE="/boot/grubMBR"
[ab82469]712
[9c535e0]713# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
[1c69be8]714if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]715then
716    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
717    then
[1c69be8]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.
[9c535e0]723        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
724        return $?
725    fi
726fi
727
728# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
[52b9a3f]729
730#llamada a updateBootCache para que aloje la primera fase del ogLive
731updateBootCache
732
[9c535e0]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
[ab82469]736
[9c535e0]737#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
[1c69be8]738[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
[9c535e0]739
740#Preparar configuración segunda etapa: crear ubicacion
741mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
[09803ea]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
[9c535e0]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}
[ab82469]751
752
753
[9c535e0]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#*/ ##
[ab82469]772
[9c535e0]773function ogGrubInstallPartition {
[ab82469]774
[9c535e0]775# Variables locales.
[1c69be8]776local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[9c535e0]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
[1c69be8]792BACKUPNAME=".backup.og"
[9c535e0]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
[1c69be8]808if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]809then
810    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
811    then
[1c69be8]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.
[9c535e0]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
[1c69be8]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
[9c535e0]829
830#Preparar configuración segunda etapa: crear ubicacion
831mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
[09803ea]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
[9c535e0]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
[ab82469]840}
841
[fd0d6e5]842
[00cede9]843#/**
[c9c2f1d1]844#         ogConfigureFstab int_ndisk int_nfilesys
[870619d]845#@brief   Configura el fstab según particiones existentes
[00cede9]846#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]847#@param   int_nfilesys   nº de orden del sistema de archivos
[00cede9]848#@return  (nada)
849#@exception OG_ERR_FORMAT    Formato incorrecto.
[c9c2f1d1]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.
[870619d]852#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
853#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
[c9c2f1d1]854#@date    2013-03-21
[870619d]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
[00cede9]858#*/ ##
859function ogConfigureFstab {
860# Variables locales.
[c9c2f1d1]861local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
[00cede9]862
863# Si se solicita, mostrar ayuda.
864if [ "$*" == "help" ]; then
[c9c2f1d1]865    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
866           "$FUNCNAME 1 1"
[00cede9]867    return
868fi
869# Error si no se reciben 2 parámetros.
870[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[c9c2f1d1]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)
[200635a]880# Configuración de swap (solo 1ª partición detectada).
881PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
[00cede9]882if [ -n "$PARTSWAP" ]
883then
[c9c2f1d1]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})
[00cede9]886    if [ -n "$DEFSWAP" ]
[c9c2f1d1]887    then
[870619d]888        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
[c9c2f1d1]889        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
[00cede9]890    else
[870619d]891        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
[c9c2f1d1]892        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
893        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
[00cede9]894    fi 
895else
[870619d]896    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
897    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
[00cede9]898fi
899}
[9c535e0]900
[c9c2f1d1]901
[764f50e]902###
903#En pruebas
904##
905#/**
[c9c2f1d1]906#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
[764f50e]907#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
908#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]909#@param   int_nfilesys   nº de orden del sistema de archivos
910#@param   str_name       nombre asignado (opcional)
[764f50e]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.
[c9c2f1d1]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
[764f50e]919#*/ ##
920function ogSetLinuxName ()
921{
922# Variables locales.
[c9c2f1d1]923local MNTDIR ETC NAME
[764f50e]924
925# Si se solicita, mostrar ayuda.
926if [ "$*" == "help" ]; then
[c9c2f1d1]927    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
928           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
[764f50e]929    return
930fi
[c9c2f1d1]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
[764f50e]942
943# Montar el sistema de archivos.
[5962edd]944MNTDIR=$(ogMount $1 $2) || return $?
[764f50e]945
946ETC=$(ogGetPath $1 $2 /etc)
947
948if [ -d "$ETC" ]; then
949        #cambio de nombre en hostname
[c9c2f1d1]950        echo "$NAME" > $ETC/hostname
[764f50e]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
[c9c2f1d1]953        #Opcion B componer fichero de hosts
954        cat > $ETC/hosts <<EOF
[764f50e]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
[df814dd0]968
[fd0d6e5]969
[df814dd0]970#/**
[c9c2f1d1]971#         ogCleanLinuxDevices int_ndisk int_nfilesys
[df814dd0]972#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
973#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]974#@param   int_nfilesys   nº de orden del sistema de archivos
[df814dd0]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.
[c9c2f1d1]979#@version 1.0.5 - Primera versión para OpenGnSys.
980#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
981#@date    2013-03-21
[fd0d6e5]982#@version 1.0.6b - Elimina fichero resume de hibernacion
983#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
984#@date    2016-11-07
[df814dd0]985#*/ ##
986function ogCleanLinuxDevices ()
987{
988# Variables locales.
[c9c2f1d1]989local MNTDIR
[df814dd0]990
991# Si se solicita, mostrar ayuda.
992if [ "$*" == "help" ]; then
[c9c2f1d1]993    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
994           "$FUNCNAME 1 1"
[df814dd0]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.
[5962edd]1001MNTDIR=$(ogMount $1 $2) || return $?
[df814dd0]1002
[c9c2f1d1]1003# Eliminar fichero de configuración de udev para dispositivos fijos de red.
[fd0d6e5]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
[df814dd0]1007}
1008
[512c692]1009#/**
[e44e88a]1010# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
[512c692]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
[1a2fa9d8]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)
[512c692]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.
[e44e88a]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
[512c692]1030#*/
1031
[e44e88a]1032function ogGrubAddOgLive () {
[1a2fa9d8]1033    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
[512c692]1034
1035    # Si se solicita, mostrar ayuda.
1036    if [ "$*" == "help" ]; then
[1a2fa9d8]1037        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1038                "$FUNCNAME 1 1" \
1039                "$FUNCNAME 1 6 15 offline"
[512c692]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 $?)
[1a2fa9d8]1045    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
[512c692]1046
1047    # Error si no existe el kernel y el initrd en la cache.
1048    # Falta crear nuevo codigo de error.
[e44e88a]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 $?)
[512c692]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
[28ffb59]1058    # Si existe la entrada de opengnsys, se borra
1059    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
[512c692]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
[e44e88a]1068    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
[1a2fa9d8]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
[512c692]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
[e44e88a]1078MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
[512c692]1079\tinsmod part_$PARTTABLETYPE \n \
1080\tinsmod ext2 \n \
1081\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1082\tlinux $KERNEL \n \
[e44e88a]1083\tinitrd /boot/${oglivedir}/oginitrd.img \n \
[512c692]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
[8196942]1099#@see ogBootLoaderHidePartitions
1100#*/
1101function ogGrubHidePartitions {
[cade8c0]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
[8196942]1108    ogBootLoaderHidePartitions $@
1109    return $?
1110}
1111
1112#/**
1113# ogBurgHidePartitions num_disk num_part
1114#@see ogBootLoaderHidePartitions
1115#*/
1116function ogBurgHidePartitions {
[cade8c0]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
[8196942]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.
[512c692]1130#@param 1 Numero de disco
1131#@param 2 Numero de particion
1132#@return  (nada)
1133#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]1134#@exception No existe archivo de configuracion del grub/burg.
[e9c3156]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
[8196942]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
[512c692]1141#*/
[8196942]1142function ogBootLoaderHidePartitions {
1143    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1144
[512c692]1145    # Si se solicita, mostrar ayuda.
1146    if [ "$*" == "help" ]; then
[cade8c0]1147        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
[512c692]1148        return
1149    fi
1150
[cade8c0]1151    # Nombre de la función que llama a esta.
1152    FUNC="${FUNCNAME[@]:1}"
1153    FUNC="${FUNC%%\ *}"
1154
[512c692]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)
[8196942]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
[512c692]1173
1174    # Error si no existe archivo del grub
[8196942]1175    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
[512c692]1176
[e9c3156]1177    # Si solo hay una particion de Windows me salgo
[8df5ab7]1178    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
[512c692]1179
1180    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
[8196942]1181    sed -i '/parttool/d' $CFGFILE
[512c692]1182
1183    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1184
1185    # Entradas de Windows: numero de linea y particion. De mayor a menor.
[8196942]1186    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
[e9c3156]1187    # Particiones de Windows, pueden no estar en el grub.
[8df5ab7]1188    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
[512c692]1189    # Modifico todas las entradas de Windows.
1190    for ENTRY in $WINENTRY; do
1191        LINE=${ENTRY%:*}
[e9c3156]1192        PART=${ENTRY#*:}
[512c692]1193        # En cada entrada, oculto o muestro cada particion.
1194        TEXT=""
[e9c3156]1195        for PART2 in $WINPART; do
[512c692]1196                # Muestro solo la particion de la entrada actual.
[e9c3156]1197                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
[512c692]1198
[26255c2]1199                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
[512c692]1200        done
1201       
[8196942]1202        sed -i "${LINE}a\ $TEXT" $CFGFILE
[512c692]1203    done
1204
1205    # Activamos la particion que se inicia en todas las entradas de windows.
[8196942]1206    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
[512c692]1207
1208}
1209
1210#/**
[be87371]1211# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
[8196942]1212#@see ogBootLoaderDeleteEntry
1213#*/
1214function ogGrubDeleteEntry {
[cade8c0]1215    # Si se solicita, mostrar ayuda.
1216    if [ "$*" == "help" ]; then
[be87371]1217        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1218                "$FUNCNAME 1 6 2 1"
[cade8c0]1219        return
1220    fi
[8196942]1221    ogBootLoaderDeleteEntry $@
1222    return $?
1223}
1224
1225#/**
[be87371]1226# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
[8196942]1227#@see ogBootLoaderDeleteEntry
1228#*/
1229function ogBurgDeleteEntry {
[cade8c0]1230    # Si se solicita, mostrar ayuda.
1231    if [ "$*" == "help" ]; then
[be87371]1232        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1233                "$FUNCNAME 1 6 2 1"
[cade8c0]1234        return
1235    fi
[8196942]1236    ogBootLoaderDeleteEntry $@
1237    return $?
1238}
1239
1240#/**
1241# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
[512c692]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
[be87371]1245#@param 3 Numero del disco del que borramos las entradas
1246#@param 4 Numero de la particion de la que borramos las entradas
[8196942]1247#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
[512c692]1248#@return  (nada)
[8196942]1249#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
[512c692]1250#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]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
[512c692]1255#*/
[8196942]1256function ogBootLoaderDeleteEntry {
1257    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
[512c692]1258
[cade8c0]1259    # Si se solicita, mostrar ayuda.
1260    if [ "$*" == "help" ]; then
1261        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1262        return
1263    fi
1264
[be87371]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
[8196942]1269    # Nombre de la función que llama a esta.
1270    FUNC="${FUNCNAME[@]:1}"
1271    FUNC="${FUNC%%\ *}"
[512c692]1272
[8196942]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
[512c692]1288
[8196942]1289    # Dispositivo
[be87371]1290    DEVICE=$(ogDiskToDev $3 $4)
[512c692]1291
1292    # Error si no existe archivo del grub)
[be87371]1293    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
[512c692]1294
[be87371]1295    # Numero de linea de cada entrada.
1296    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
[512c692]1297
1298    # Entradas que hay que borrar.
[be87371]1299    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
[8196942]1300
1301    # Si no hay entradas para borrar me salgo con aviso
[be87371]1302    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
[512c692]1303
1304    # Recorremos el fichero del final hacia el principio.
[8196942]1305    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
[512c692]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
[8196942]1310            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
[512c692]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
[8196942]1318
[74e01a7]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.
[c0fde6d]1327#@exception OG_ERR_PARTITION  Partición no soportada
[74e01a7]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
[19c9dca]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
[74e01a7]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)
[19c9dca]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;
[74e01a7]1370
1371#Copiamos el tema
1372mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
[19c9dca]1373cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
[74e01a7]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
[19c9dca]1383        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]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
[19c9dca]1493burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]1494}
1495
[0d2e65b]1496#/**
[be87371]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
[0d2e65b]1528#@brief   Configura la entrada por defecto de Burg
1529#@param   int_disk_SecondStage     
1530#@param   int_part_SecondStage     
[be87371]1531#@param   int_disk_default_entry
1532#@param   int_part_default_entry
[0d2e65b]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.
[be87371]1538#@version 1.1.0 - Define la entrada por defecto del Burg
[0d2e65b]1539#@author  Irina Gomez, ETSII Universidad de Sevilla
1540#@date    2017-08-09
[be87371]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
[0d2e65b]1544#*/ ##
[be87371]1545function ogBootLoaderDefaultEntry {
[0d2e65b]1546
1547# Variables locales.
[be87371]1548local PART CFGFILE DEFAULTENTRY MSG
[0d2e65b]1549
1550# Si se solicita, mostrar ayuda.
1551if [ "$*" == "help" ]; then
[be87371]1552    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
[0d2e65b]1553    return
1554fi 
1555
[be87371]1556# Nombre de la función que llama a esta.
1557FUNC="${FUNCNAME[@]:1}"
1558FUNC="${FUNC%%\ *}"
1559
[0d2e65b]1560# Error si no se reciben 3 parametros.
[be87371]1561[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
[0d2e65b]1562
1563# Error si no puede montar sistema de archivos.
[be87371]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)
[0d2e65b]1586
[be87371]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)
[0d2e65b]1589
[be87371]1590# Si no hay entradas para borrar me salgo con aviso
1591[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
[0d2e65b]1592
[be87371]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
[0d2e65b]1597
[be87371]1598sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1599
1600MSG="MSG_HELP_$FUNC"
1601echo "${!MSG%%\.}: $@"
[0d2e65b]1602}
1603
1604#/**
[be87371]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
[0d2e65b]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
[be87371]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
[0d2e65b]1650#*/ ##
[be87371]1651function  ogBootLoaderOgliveDefaultEntry {
[0d2e65b]1652
1653# Variables locales.
[be87371]1654local FUNC PART CFGFILE NUMENTRY MSG
[0d2e65b]1655
1656# Si se solicita, mostrar ayuda.
1657if [ "$*" == "help" ]; then
[be87371]1658    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
[0d2e65b]1659    return
1660fi 
1661
[be87371]1662# Nombre de la función que llama a esta.
1663FUNC="${FUNCNAME[@]:1}"
1664FUNC="${FUNC%%\ *}"
1665
[0d2e65b]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 $?
[be87371]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
[0d2e65b]1684
[be87371]1685# Comprobamos que exista fichero de configuración
1686[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
[0d2e65b]1687
1688# Detectamos cual es la entrada de ogLive
[be87371]1689NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
[0d2e65b]1690
1691# Si no existe entrada de ogLive nos salimos
[be87371]1692[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
[0d2e65b]1693
1694let NUMENTRY=$NUMENTRY-1
[f2e6a2e]1695sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
[0d2e65b]1696
[be87371]1697MSG="MSG_HELP_$FUNC"
1698echo "${!MSG%%\.}: $@"
[0d2e65b]1699}
[74e01a7]1700
Note: See TracBrowser for help on using the repository browser.