source: client/engine/Boot.lib @ c90cda4

Last change on this file since c90cda4 was 9fe0fe3, checked in by Irina Gómez <irinagomez@…>, 5 years ago

#841 Fixes bug in partitioning wizard when configure MBR: ogGetBootMbr function is created for detect MBR content and used in wizard.

  • Property mode set to 100755
File size: 103.6 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
[b7dc4ac]40#@version 1.1.1 - UEFI: Permite iniciar linux recien instalados (ticket #802 #890)
41#@author  Irina Gomez, ETSII Universidad de Sevilla
42#@date    2019-03-13
[1e7eaab]43#*/ ##
[42669ebf]44function ogBoot ()
45{
[b094c59]46# Variables locales.
[40ad2e8d]47local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
[b7dc4ac]48local EFIDISK EFIPART EFIDIR BOOTLABEL BOOTLOADER BOOTNO DIRGRUB b
[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)}"
[b7dc4ac]69        # Si no existe y el UEFI buscar en particion ESP
[47d8ae8]70        [ -z "$PARAMS" ] && ogIsEfiActive && PARAMS="$(ogLinuxBootParameters $(ogGetEsp))"
[21815bd5]71        # Si no existe, buscar sistema de archivo /boot en /etc/fstab.
72        if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then
73            # Localizar S.F. /boot en /etc/fstab del S.F. actual.
[da82642]74            PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
[8fc2631]75            # Montar S.F. de /boot.
76            MNTDIR=$(ogMount $PART) || return $?
[21815bd5]77            # Buscar los datos de arranque.
78            PARAMS=$(ogLinuxBootParameters $PART) || exit $?
79        fi
[f5432db7]80        read -e KERNEL INITRD APPEND <<<"$PARAMS"
[1e7eaab]81        # Si no hay kernel, no hay sistema operativo.
[6893030]82        [ -n "$KERNEL" -a -e "$MNTDIR/$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
[1e7eaab]83        # Arrancar de partición distinta a la original.
[049eadbe]84        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
[6893030]85        # Comprobar tipo de sistema.
86        if ogIsEfiActive; then
87            # Comprobar si el Kernel está firmado.
[d2a274a]88            if ! file -k "$MNTDIR/$KERNEL" | grep -q "EFI app"; then
[b242c72]89                ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)"
[6893030]90                return $?
91            fi
[39b84ff]92
93            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
[3f4a9b7]94            BOOTLOADER="shimx64.efi"
[b7dc4ac]95            # Obtener parcición EFI.
96            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
97            # TODO: Comprobamos que existe la BOOTLABEL, si no buscamos por sistema operativo
98            if [ "$(ogGetPath $EFIDISK $EFIPART EFI/$BOOTLABEL)" == "" ]; then
99                OSVERSION="$(ogGetOsVersion $1 $2)"
100                case $OSVERSION in
101                    *SUSE*)
102                       BOOTLABEL="opensuse"
103                       ;;
104                    *Fedora*)
105                       BOOTLABEL="fedora"
106                       ;;
107                    *Ubuntu*)
108                       BOOTLABEL="ubuntu"
109                       ;;
110                    *)
111                       ogRaiseError $OG_ERR_NOTFOUND "$EFIDISK $EFIPART Boot loader"; return $?
112                       ;;
113                esac
114            fi
115
116            # Crear orden de arranque (con unos valores por defecto).
[3f4a9b7]117            ogNvramAddEntry $BOOTLABEL "/EFI/$BOOTLABEL/Boot/$BOOTLOADER"
[6893030]118            # Marcar próximo arranque y reiniciar.
[3f4a9b7]119            ogNvramSetNext "$BOOTLABEL"
[6893030]120            reboot
121        else
122            # Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB.
123            kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
[40ad2e8d]124            kexec -e &
[6893030]125        fi
126        ;;
127    Windows)
128        # Comprobar tipo de sistema.
129        if ogIsEfiActive; then
[20e5aa9e]130            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
[6893030]131            # Obtener parcición EFI.
132            read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
133            [ -n "$EFIPART" ] || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
134            EFIDIR=$(ogMount $EFIDISK $EFIPART) || exit $?
[b242c72]135            # Comprobar cargador (si no existe buscar por defecto en ESP).
[20e5aa9e]136            LOADER=$(ogGetPath $EFIDIR/EFI/$BOOTLABEL/Boot/bootmgfw.efi)
137            [ -z "$LOADER" ] && BOOTLABEL=Microsoft && LOADER=$(ogGetPath $EFIDIR/EFI/Microsoft/Boot/bootmgfw.efi)
[b242c72]138            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)" || return $?
[527cd97]139
[6893030]140            # Crear orden de arranque (con unos valores por defecto).
[527cd97]141            ogNvramAddEntry $BOOTLABEL "/EFI${LOADER#*EFI}"
[6893030]142            # Marcar próximo arranque y reiniciar.
[527cd97]143            ogNvramSetNext "$BOOTLABEL"
[6893030]144            reboot
[40ad2e8d]145        else
[20e5aa9e]146            # Arranque BIOS: comprueba si hay un cargador de Windows.
[6893030]147            for f in io.sys ntldr bootmgr; do
148                FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
149                [ -n "$FILE" ] && LOADER="$f"
150            done
151            [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
152            if [ "$winboot" == "kexec" ]; then
153                # Modo de arranque en caliente (con kexec).
154                cp $OGLIB/grub4dos/* $MNTDIR    # */ (Comentario Doxygen)
155                kexec -l $MNTDIR/grub.exe --append=--config-file="root (hd$[$1-1],$[$2-1]); chainloader (hd$[$1-1],$[$2-1])/$LOADER; tpm --init"
156                kexec -e &
157            else
158                # Modo de arranque por reinicio (con reboot).
159                dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3
160                dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3
161                dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3
162                if  [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then
163                    ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot'
164                    ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*"
165                fi
166                # Activar la partición.
167                ogSetPartitionActive $1 $2
168                reboot
[fc65d8d9]169            fi
[75a296b]170        fi
[f5432db7]171        ;;
[2b2f533]172    MacOS)
173        # Modo de arranque por reinicio.
174        # Nota: el cliente tiene que tener configurado correctamente Grub.
175        touch ${MNTDIR}/boot.mac &>/dev/null
176        reboot
177        ;;
178    GrubLoader)
179        # Reiniciar.
[30238ab]180        #reboot
[2b2f533]181        ;;
[477ba42]182    *)  ogRaiseError $OG_ERR_NOTOS "$1 $2 ${TYPE:+($TYPE)}"
[326cec3]183        return $?
[f5432db7]184        ;;
[b094c59]185esac
186}
187
188
189#/**
[16360e4]190#         ogGetWindowsName int_ndisk int_nfilesys
[3e1561d]191#@brief   Muestra el nombre del equipo en el registro de Windows.
[42669ebf]192#@param   int_ndisk      nº de orden del disco
[16360e4]193#@param   int_nfilesys   nº de orden del sistema de archivos
[3e1561d]194#@return  str_name - nombre del equipo
195#@exception OG_ERR_FORMAT    Formato incorrecto.
196#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
197#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]198#@version 0.9 - Adaptación para OpenGnSys.
[3e1561d]199#@author  Ramon Gomez, ETSII Universidad de Sevilla
200#@date    2009-09-23
[1e7eaab]201#*/ ##
[42669ebf]202function ogGetWindowsName ()
203{
[3e1561d]204# Variables locales.
[c198e60]205local MNTDIR
[3e1561d]206
[1e7eaab]207# Si se solicita, mostrar ayuda.
[3e1561d]208if [ "$*" == "help" ]; then
209    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
210           "$FUNCNAME 1 1  ==>  PRACTICA-PC"
211    return
212fi
[1e7eaab]213# Error si no se reciben 2 parámetros.
[3e1561d]214[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
215
[1e7eaab]216# Montar el sistema de archivos.
[5962edd]217MNTDIR=$(ogMount $1 $2) || return $?
[3e1561d]218
[1e7eaab]219# Obtener dato del valor de registro.
[3e1561d]220ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
221}
222
223
224#/**
[b94c497]225#         ogLinuxBootParameters int_ndisk int_nfilesys
[b094c59]226#@brief   Muestra los parámetros de arranque de un sistema de archivos Linux.
[42669ebf]227#@param   int_ndisk      nº de orden del disco
[b94c497]228#@param   int_nfilesys   nº de orden del sistema de archivos
[42669ebf]229#@return  str_kernel str_initrd str_parameters ...
[b094c59]230#@exception OG_ERR_FORMAT    Formato incorrecto.
231#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
232#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[055adcf]233#@warning Función básica usada por \c ogBoot
[3915005]234#@version 0.9 - Primera adaptación para OpenGnSys.
[b094c59]235#@author  Ramon Gomez, ETSII Universidad de Sevilla
236#@date    2009-09-11
[199bdf3]237#@version 0.9.2 - Soporta partición /boot independiente.
238#@author  Ramon Gomez, ETSII Universidad de Sevilla
239#@date    2010-07-20
[b94c497]240#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
241#@author  Ramon Gomez, ETSII Universidad de Sevilla
242#@date    2013-05-14
[6647a20]243#@version 1.0.6 - Detectar instalaciones sobre EFI.
244#@author  Ramon Gomez, ETSII Universidad de Sevilla
245#@date    2014-09-15
[1e7eaab]246#*/ ##
[42669ebf]247function ogLinuxBootParameters ()
248{
[b094c59]249# Variables locales.
[6647a20]250local MNTDIR CONFDIR CONFFILE f
[b094c59]251
[1e7eaab]252# Si se solicita, mostrar ayuda.
[b094c59]253if [ "$*" == "help" ]; then
[b94c497]254    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
255           "$FUNCNAME 1 2  ==>  /vmlinuz-3.5.0-21-generic /initrd.img-3.5.0-21-generic root=/dev/sda2 ro splash"
[b094c59]256    return
257fi
[1e7eaab]258# Error si no se reciben 2 parámetros.
[b094c59]259[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
260
[1e7eaab]261# Detectar id. de tipo de partición y codificar al mnemonico.
[5962edd]262MNTDIR=$(ogMount $1 $2) || return $?
[b094c59]263
264# Fichero de configuración de GRUB.
[6647a20]265CONFDIR=$MNTDIR                               # Sistema de archivos de arranque (/boot).
266[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot   # Sist. archivos raíz con directorio boot.
[58f59ce]267for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{2,},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
[6647a20]268    [ -r $f ] && CONFFILE=$f
269done
[cf8a0ae]270[ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
[b094c59]271
[1e7eaab]272# Toma del fichero de configuracion los valores del kernel, initrd
[ee4a96e]273#       y parámetros de arranque usando las cláusulas por defecto
274#       ("default" en GRUB1, "set default" en GRUB2)
275#       y los formatea para que sean compatibles con \c kexec .  */
[1e7eaab]276# /* (comentario Doxygen)
[b094c59]277awk 'BEGIN {cont=-1;}
[b94c497]278     $1~/^default$/     {sub(/=/," "); def=$2;}
[6647a20]279     $1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3;
[b94c497]280                                   if (def ~ /saved_entry/) def=0;
[6647a20]281                                 }
[b94c497]282     $1~/^(title|menuentry)$/ {cont++}
[529c585]283     $1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; }
[8fc2631]284     $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
[6647a20]285                                       kern=$2;
286                                       sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
[8fc2631]287                                      } # /* (comentario Doxygen)
288                                    }
289     $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
[b094c59]290     END {if (kern!="") printf("%s %s %s", kern,init,app)}
[199bdf3]291    ' $CONFFILE
[1e7eaab]292# */ (comentario Doxygen)
[b094c59]293}
294
[3e1561d]295
296#/**
[e538e62]297#         ogSetWindowsName int_ndisk int_nfilesys str_name
[3e1561d]298#@brief   Establece el nombre del equipo en el registro de Windows.
[42669ebf]299#@param   int_ndisk      nº de orden del disco
[e538e62]300#@param   int_nfilesys   nº de orden del sistema de archivos
[42669ebf]301#@param   str_name       nombre asignado
[3e1561d]302#@return  (nada)
[e538e62]303#@exception OG_ERR_FORMAT     Formato incorrecto.
304#@exception OG_ERR_NOTFOUND   Disco o particion no corresponden con un dispositivo.
305#@exception OG_ERR_PARTITION  Tipo de partición desconocido o no se puede montar.
306#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
[3915005]307#@version 0.9 - Adaptación a OpenGnSys.
[3e1561d]308#@author  Ramon Gomez, ETSII Universidad de Sevilla
309#@date    2009-09-24
[e538e62]310#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
311#@author  Ramon Gomez, ETSII Universidad de Sevilla
312#@date    2013-03-20
[1e7eaab]313#*/ ##
[42669ebf]314function ogSetWindowsName ()
315{
[3e1561d]316# Variables locales.
317local PART MNTDIR NAME
318
[1e7eaab]319# Si se solicita, mostrar ayuda.
[3e1561d]320if [ "$*" == "help" ]; then
[e538e62]321    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
[3e1561d]322           "$FUNCNAME 1 1 PRACTICA-PC"
323    return
324fi
[1e7eaab]325# Error si no se reciben 3 parámetros.
[3e1561d]326[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[e538e62]327# Error si el nombre supera los 15 caracteres.
328[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
[3e1561d]329
[42669ebf]330# Montar el sistema de archivos.
[5962edd]331MNTDIR=$(ogMount $1 $2) || return $?
332
333# Asignar nombre.
[3e1561d]334NAME="$3"
335
[1e7eaab]336# Modificar datos de los valores de registro.
[4b9cdda]337ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
338ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
[42e8020]339ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\HostName' "$NAME" 2>/dev/null
[4b9cdda]340ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
341ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
[42e8020]342ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV HostName' "$NAME" 2>/dev/null
[4b9cdda]343ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
[3e1561d]344}
345
[f5432db7]346
[4b9cdda]347#/**
348#         ogSetWinlogonUser int_ndisk int_npartition str_username
349#@brief   Establece el nombre de usuario por defecto en la entrada de Windows.
350#@param   int_ndisk      nº de orden del disco
351#@param   int_npartition nº de orden de la partición
352#@param   str_username   nombre de usuario por defecto
353#@return  (nada)
354#@exception OG_ERR_FORMAT    Formato incorrecto.
355#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
356#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]357#@version 0.9.2 - Adaptación a OpenGnSys.
[4b9cdda]358#@author  Ramon Gomez, ETSII Universidad de Sevilla
359#@date    2010-07-20
360#*/ ##
361function ogSetWinlogonUser ()
362{
363# Variables locales.
364local PART MNTDIR NAME
365
366# Si se solicita, mostrar ayuda.
367if [ "$*" == "help" ]; then
368    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
369           "$FUNCNAME 1 1 USUARIO"
370    return
371fi
372# Error si no se reciben 3 parámetros.
373[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
374
375# Montar el sistema de archivos.
[5962edd]376MNTDIR=$(ogMount $1 $2) || return $?
377
378# Asignar nombre.
[4b9cdda]379NAME="$3"
380
381# Modificar datos en el registro.
382ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
383}
384
[38231e9]385
386#/**
[9e8773c]387#         ogBootMbrXP int_ndisk
[38231e9]388#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
[42669ebf]389#@param   int_ndisk      nº de orden del disco
[945b003]390#@return  salida del programa my-sys
[38231e9]391#@exception OG_ERR_FORMAT    Formato incorrecto.
392#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]393#@version 0.9 - Adaptación a OpenGnSys.
[38231e9]394#@author  Antonio J. Doblas Viso. Universidad de Málaga
395#@date    2009-09-24
396#*/ ##
397
[9e8773c]398function ogBootMbrXP ()
[e05993a]399{
[38231e9]400# Variables locales.
[a73649d]401local DISK
[38231e9]402
403# Si se solicita, mostrar ayuda.
404if [ "$*" == "help" ]; then
405    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
[a73649d]406           "$FUNCNAME 1"
[38231e9]407    return
[945b003]408fi
[a73649d]409# Error si no se recibe 1 parámetro.
[38231e9]410[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
411
[a73649d]412DISK="$(ogDiskToDev $1)" || return $?
413ms-sys -z -f $DISK
414ms-sys -m -f $DISK
[945b003]415}
[42669ebf]416
[fdad5a6]417
[9e8773c]418#/**
419#         ogBootMbrGeneric int_ndisk
420#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
421#@param   int_ndisk      nº de orden del disco
422#@return  salida del programa my-sys
423#@exception OG_ERR_FORMAT    Formato incorrecto.
424#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
[3915005]425#@version 0.9 - Adaptación a OpenGnSys.
[9e8773c]426#@author  Antonio J. Doblas Viso. Universidad de Málaga
427#@date    2009-09-24
428#*/ ##
429
430function ogBootMbrGeneric ()
431{
432# Variables locales.
[a73649d]433local DISK
[9e8773c]434
435# Si se solicita, mostrar ayuda.
436if [ "$*" == "help" ]; then
437    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
438           "$FUNCNAME 1 "
439    return
440fi
[a73649d]441# Error si no se recibe 1 parámetro.
[9e8773c]442[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
443
[a73649d]444DISK="$(ogDiskToDev $1)" || return $?
445ms-sys -z -f $DISK
446ms-sys -s -f $DISK
[9e8773c]447}
448
449
450
[fdad5a6]451
452#/**
453#         ogFixBootSector int_ndisk int_parition
454#@brief   Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
455#@param   int_ndisk      nº de orden del disco
456#@param   int_partition     nº de particion
457#@return 
458#@exception OG_ERR_FORMAT    Formato incorrecto.
459#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]460#@version 0.9 - Adaptación a OpenGnSys.
[fdad5a6]461#@author  Antonio J. Doblas Viso. Universidad de Málaga
462#@date    2009-09-24
463#*/ ##
464
465function ogFixBootSector ()
466{
467# Variables locales.
[1cd64e6]468local PARTYPE DISK PART FILE
[fdad5a6]469
470# Si se solicita, mostrar ayuda.
471if [ "$*" == "help" ]; then
472    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
473           "$FUNCNAME 1 1 "
474    return
475fi
476
477# Error si no se reciben 2 parámetros.
478[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
479
480#TODO, solo si la particion existe
481#TODO, solo si es ntfs o fat
482PARTYPE=$(ogGetPartitionId $1 $2)
[3915005]483case "$PARTYPE" in
[20e5aa9e]484        1|4|6|7|b|c|e|f|17|700|EF00)
[fdad5a6]485        ;;
486        *)
487        return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
488        ;;
489esac
490
491ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
492
493#Preparando instruccion
494let DISK=$1-1   
495PART=$2
[1cd64e6]496FILE=/tmp/temp$$
[fdad5a6]497cat > $FILE <<EOF
498disk=$DISK
499main_part=$PART
500fix_first_sector=yes
501EOF
502
[20e5aa9e]503timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -a -f $FILE
[1cd64e6]504rm -f $FILE
[fdad5a6]505}
506
507
[9fe0fe3]508#/**
509#         ogGetBootMbr int_ndisk
510#@brief   Obtiene el contenido del sector de arranque de un disco.
511#@param   int_ndisk     nº de orden del disco
512#@return  str_MBR       Descripción del contenido del MBR.
513#@exception OG_ERR_FORMAT    Formato incorrecto.
514#@exception OG_ERR_NOTFOUND  Dispositivo de disco no encontrado.
515#@version 1.1.1b - Primera versión
516#@author  Irina Gómez (US). Propuesto por Antonio J. Doblas Viso (UMA)
517#@date    2020-04-05
518#*/ ##
519function ogGetBootMbr ()
520{
521# Variables locales.
522local DISK
523
524# Si se solicita, mostrar ayuda.
525if [ "$*" == "help" ]; then
526    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
527           "$FUNCNAME 1"
528    return
529fi
530
531# Error si no se recibe 1 parámetro.
532[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndisk" || return $?
533
534DISK="$(ogDiskToDev $1)" || return $?
535
536ms-sys -f $DISK
537}
[fdad5a6]538
539#/**
540#         ogWindowsBootParameters int_ndisk int_parition
[78b5dfe7]541#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
[fdad5a6]542#@param   int_ndisk      nº de orden del disco
543#@param   int_partition     nº de particion
544#@return 
545#@exception OG_ERR_FORMAT    Formato incorrecto.
546#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]547#@version 0.9 - Integración desde EAC para OpenGnSys.
[fdad5a6]548#@author  Antonio J. Doblas Viso. Universidad de Málaga
549#@date    2009-09-24
[78b5dfe7]550#@version 1.0.1 - Adapatacion para OpenGnsys.
551#@author  Antonio J. Doblas Viso. Universidad de Málaga
552#@date    2011-05-20
[e763190]553#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
554#@author  Ramon Gomez, ETSII Universidad de Sevilla
555#@date    2014-01-28
[b6971f1]556#@version 1.1.0 - Soporte para Windows 10.
557#@author  Ramon Gomez, ETSII Universidad de Sevilla
558#@date    2016-01-19
[20e5aa9e]559#@version 1.1.1 - Compatibilidad con UEFI (ticket #802 #889)
560#@author  Irina Gomez, ETSII Universidad de Sevilla
561#@date    2019-01-28
[fdad5a6]562#*/ ##
563
564function ogWindowsBootParameters ()
565{
566# Variables locales.
[20e5aa9e]567local PART DISK BOOTLABEL BCDFILE BOOTDISK BOOTPART FILE WINVER MOUNT
[fdad5a6]568
569# Si se solicita, mostrar ayuda.
570if [ "$*" == "help" ]; then
571    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
572           "$FUNCNAME 1 1 "
573    return
574fi
575
576# Error si no se reciben 2 parámetros.
577[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
578
579ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
580
[e763190]581#Preparando variables adaptadas a sintaxis windows.
582let DISK=$1-1
583PART=$2
584FILE=/tmp/temp$$
[47d8ae8]585if ogIsEfiActive; then
[20e5aa9e]586    read BOOTDISK BOOTPART <<< $(ogGetEsp)
587    ogUnmount $BOOTDISK $BOOTPART || ogRaiseError $OG_ERR_PARTITION "ESP: $BOOTDISK $BOOTPART" || return $?
588
589    let BOOTDISK=$BOOTDISK-1
590    BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
591    BCDFILE="boot_BCD_file=/EFI/$BOOTLABEL/Boot/BCD"
592else
593    BOOTDISK=$DISK
594    BOOTPART=$PART
595    BCDFILE=""
596fi
597
[e763190]598
[ccf1fa0]599# Obtener versión de Windows.
[1e4000f]600WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
[ccf1fa0]601[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?)
602
603# Acciones para Windows XP.
604if [[ "$WINVER" =~ "XP" ]]; then
605    MOUNT=$(ogMount $1 $2)
606    [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?)
607    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
608    return 0
[fdad5a6]609fi
610
611ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
[78b5dfe7]612
[fdad5a6]613
614#Preparando instruccion Windows Resume Application
615cat > $FILE <<EOF
[20e5aa9e]616boot_disk=$BOOTDISK
617boot_main_part=$BOOTPART
618$BCDFILE
[fdad5a6]619disk=$DISK
620main_part=$PART
621boot_entry=Windows Resume Application
622EOF
[20e5aa9e]623timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[5fde4bc]624
[fdad5a6]625
626#Preparando instruccion tipo windows
627cat > $FILE <<EOF
[20e5aa9e]628boot_disk=$BOOTDISK
629boot_main_part=$BOOTPART
630$BCDFILE
[fdad5a6]631disk=$DISK
632main_part=$PART
633boot_entry=$WINVER
634EOF
[20e5aa9e]635timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[fdad5a6]636
[250742d]637##Preparando instruccion        Ramdisk Options
[5fde4bc]638cat > $FILE <<EOF
[20e5aa9e]639boot_disk=$BOOTDISK
640boot_main_part=$BOOTPART
641$BCDFILE
[5fde4bc]642disk=$DISK
643main_part=$PART
644boot_entry=Ramdisk Options
645EOF
[20e5aa9e]646timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[5fde4bc]647
[20e5aa9e]648##Preparando instruccion        Recovery Environment
649cat > $FILE <<EOF
650boot_disk=$BOOTDISK
651boot_main_part=$BOOTPART
652$BCDFILE
653disk=$DISK
654main_part=$PART
655boot_entry=Windows Recovery Environment
656EOF
657timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[fdad5a6]658
[20e5aa9e]659##Preparando instruccion        Recovery
[fdad5a6]660cat > $FILE <<EOF
[20e5aa9e]661boot_disk=$BOOTDISK
662boot_main_part=$BOOTPART
663$BCDFILE
[fdad5a6]664disk=$DISK
665main_part=$PART
[20e5aa9e]666boot_entry=Windows Recovery
[fdad5a6]667EOF
[20e5aa9e]668timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[5fde4bc]669
[20e5aa9e]670#Preparando instruccion Windows Boot Manager
671cat > $FILE <<EOF
672boot_disk=$BOOTDISK
673boot_main_part=$BOOTPART
674$BCDFILE
675disk=$BOOTDISK
676main_part=$BOOTPART
677boot_entry=Windows Boot Manager
678EOF
679timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[fdad5a6]680
681#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
[5fde4bc]682cat > $FILE <<EOF
[20e5aa9e]683boot_disk=$BOOTDISK
684boot_main_part=$BOOTPART
685$BCDFILE
686disk=$BOOTDISK
687main_part=$BOOTPART
[5fde4bc]688boot_entry=Herramienta de diagnóstico de memoria de Windows
689EOF
[20e5aa9e]690timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
691
692#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
693cat > $FILE <<EOF
694boot_disk=$BOOTDISK
695boot_main_part=$BOOTPART
696$BCDFILE
697disk=$BOOTDISK
698main_part=$BOOTPART
699boot_entry=Herramienta de diagn<f3>stico de memoria de Windows
700EOF
701timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
[fdad5a6]702
[20e5aa9e]703rm -f $FILE
[fdad5a6]704}
[3915005]705
[fdad5a6]706
[872b044]707
708#/**
[78b5dfe7]709#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
[fdad5a6]710#@brief   Registra una partición en windows con un determinado volumen.
711#@param   int_ndisk      nº de orden del disco a registrar
712#@param   int_partition     nº de particion a registrar
713#@param   str_volumen      volumen a resgistar
714#@param   int_ndisk_windows      nº de orden del disco donde esta windows
715#@param   int_partition_windows     nº de particion donde esta windows
716#@return 
717#@exception OG_ERR_FORMAT    Formato incorrecto.
718#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[3915005]719#@version 0.9 - Adaptación a OpenGnSys.
[fdad5a6]720#@author  Antonio J. Doblas Viso. Universidad de Málaga
721#@date    2009-09-24
722#*/ ##
[78b5dfe7]723function ogWindowsRegisterPartition ()
[3915005]724{
[fdad5a6]725# Variables locales.
[3915005]726local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
[fdad5a6]727
728# Si se solicita, mostrar ayuda.
729if [ "$*" == "help" ]; then
730    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
731           "$FUNCNAME 1 1 c: 1 1"
732    return
733fi
734
735# Error si no se reciben 5 parámetros.
736[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
737
738REGISTREDDISK=$1
739REGISTREDPART=$2
740REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
741DISK=$4
742PART=$5
[3915005]743FILE=/tmp/temp$$
[fdad5a6]744
745ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
746ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
747
748ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
749
750VERSION=$(ogGetOsVersion $DISK $PART)
751
752#Systemroot
753
754if ogGetPath $DISK $PART WINDOWS
755then
756        SYSTEMROOT="Windows"
757elif ogGetPath $DISK $PART WINNT
758then
759        SYSTEMROOT="winnt"
760else
761        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
762fi
763
764ogUnmount $DISK $PART
765let DISK=$DISK-1
766let REGISTREDDISK=$REGISTREDDISK-1
767#Preparando instruccion Windows Boot Manager
768cat > $FILE <<EOF
769windows_disk=$DISK
770windows_main_part=$PART
771windows_dir=$SYSTEMROOT
772disk=$REGISTREDDISK
773main_part=$REGISTREDPART
774;ext_part
775part_letter=$REGISTREDVOL
776EOF
[20e5aa9e]777timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -u -f $FILE
[5fde4bc]778
[e0c0d93]779}
[ab82469]780
[872b044]781#/**
[59c5b66]782#         ogGrubInstallMbr  int_disk_GRUBCFG  int_partition_GRUBCFG 
783#@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]784#@param   int_disk_SecondStage     
785#@param   int_part_SecondStage     
786#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
[ab82469]787#@return 
788#@exception OG_ERR_FORMAT    Formato incorrecto.
789#@version 1.0.2 - Primeras pruebas.
790#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
791#@date    2011-10-29
[9c535e0]792#@version 1.0.3 - Soporte para linux de 32 y 64 bits
793#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
794#@date    2012-03-13
795#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
796#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
797#@date    2012-03-13
[59c5b66]798#@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.
799#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
800#@date    2017-06-19
[59cebeed]801#@version 1.1.0 - #827 Entrada para el ogLive si el equipo tiene partición cache.
802#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
803#@date    2018-01-21
[30238ab]804#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
805#@author Irina Gomez, ETSII Universidad de Sevilla
[7dc06be9]806#@date    2019-01-08
[3673737]807#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
808#@author  Irina Gomez, ETSII Universidad de Sevilla
809#@date    2019-03-05
[ab82469]810#*/ ##
811
[d2c8674]812function ogGrubInstallMbr ()
813{
[ab82469]814
815# Variables locales.
[1c69be8]816local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[d0bf22a]817local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB GRUBENTRY NEWORDER
[ab82469]818
819# Si se solicita, mostrar ayuda.
820if [ "$*" == "help" ]; then
[9c535e0]821    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
822           "$FUNCNAME 1 1 FALSE " \
823           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
[ab82469]824    return
[9c535e0]825fi 
[ab82469]826
827# Error si no se reciben 2 parámetros.
[9c535e0]828[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
[ab82469]829
830
[9c535e0]831DISK=$1; PART=$2;
832CHECKOS=${3:-"FALSE"}
833KERNELPARAM=$4
[1c69be8]834BACKUPNAME=".backup.og"
[ab82469]835
[9c535e0]836#Error si no es linux.
837#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
[a4b1e2a]838#VERSION=$(ogGetOsVersion $DISK $PART)
839#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
[ab82469]840
[59c5b66]841#La primera etapa del grub se fija en el primer disco duro
842FIRSTSTAGE=$(ogDiskToDev 1)
[ab82469]843
[9c535e0]844#localizar disco segunda etapa del grub
[39b84ff]845SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
[ab82469]846
[a4b1e2a]847# prepara el directorio principal de la segunda etapa
848[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
849
[9c535e0]850#Localizar directorio segunda etapa del grub   
851PREFIXSECONDSTAGE="/boot/grubMBR"
[ab82469]852
[39b84ff]853# Instalamos grub para EFI en ESP
[3f4a9b7]854EFIOPTGRUB=""
[39b84ff]855if ogIsEfiActive; then
856    read EFIDISK EFIPART <<< $(ogGetEsp)
857    # Comprobamos que exista ESP y el directorio para ubuntu
[e9601e1]858    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
859    if [ $? -ne 0 ]; then
860        ogFormat $EFIDISK $EFIPART FAT32
861        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
862    fi
[d61c5e5]863    EFISUBDIR="grub"
[3673737]864    # Borramos la configuración anterior
865    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
866    mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
[3f4a9b7]867    EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
[39b84ff]868fi
869
[9c535e0]870# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
[3f4a9b7]871if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]872then
[1c69be8]873        # Si no se reconfigura se utiliza el grub.cfg orginal
874        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
[3f4a9b7]875        # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
[1c69be8]876        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
[67b3142]877        PREFIXSECONDSTAGE=""
[3f4a9b7]878else
879        # SI Reconfigurar segunda etapa (grub.cfg) == TRUE
[40bd9f5]880
[3f4a9b7]881        #llamada a updateBootCache para que aloje la primera fase del ogLive
882        updateBootCache
[9c535e0]883
[3f4a9b7]884        if ogIsEfiActive; then
885            # UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
886            if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
887                 [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
888            fi
889        else
890            #Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
891            mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
892        fi
[52b9a3f]893
[3f4a9b7]894        #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
895        echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
896        echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
[52b9a3f]897
[3673737]898
[3f4a9b7]899        #Preparar configuración segunda etapa: crear ubicacion
900        mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
901        #Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
902        sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
[8b5283a]903        # (ogLive 5.0) Si 'pkgdatadir' está vacía ponemos valor de otros ogLive
904        sed -i '/grub-mkconfig_lib/i\pkgdatadir=${pkgdatadir:-"${datarootdir}/grub"}' /etc/grub.d/00_header
[3f4a9b7]905        /etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
[8b5283a]906
[3f4a9b7]907        #Preparar configuración segunda etapa: crear entrada del sistema operativo
908        grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
[ab82469]909
[3f4a9b7]910        # Renombramos la configuración de grub antigua
911        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
[9c535e0]912
[3f4a9b7]913fi
[7dc06be9]914
[67b3142]915#Instalar el grub
916grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
917EVAL=$?
918
[7dc06be9]919# Movemos el grubx64.efi
[39b84ff]920if ogIsEfiActive; then
[3f4a9b7]921    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
[7dc06be9]922    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
[dd890f1]923    cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi
[3f4a9b7]924    # Nombre OpenGnsys para cargador
[dd890f1]925    cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi}
[d0bf22a]926
927    # Creamos entrada NVRAM y la ponemos en segundo lugar
928    ogNvramAddEntry grub /EFI/grub/Boot/shimx64.efi
[a4f15eb]929    GRUBENTRY=$(ogNvramList| awk '{if ($2=="grub") print $1}')
[d0bf22a]930    NEWORDER="$(ogNvramGetOrder|awk -v ENTRY=$GRUBENTRY '{gsub(",", " "); printf "%x %x %s\n", $1 , ENTRY , substr($0, index($0,$2))}')"
931    ogNvramSetOrder $NEWORDER
[39b84ff]932fi
[3f4a9b7]933return $EVAL
[67b3142]934
[9c535e0]935}
[ab82469]936
937
[872b044]938#/**
[9c535e0]939#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
940#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
941#@param   int_disk_SecondStage     
942#@param   int_part_SecondStage     
943#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
944#@param   str "kernel param "   
945#@return 
946#@exception OG_ERR_FORMAT    Formato incorrecto.
947#@version 1.0.2 - Primeras pruebas.
948#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
949#@date    2011-10-29
950#@version 1.0.3 - Soporte para linux de 32 y 64 bits
951#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
952#@date    2012-03-13
953#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
954#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
955#@date    2012-03-13
[30238ab]956#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
957#@author Irina Gomez, ETSII Universidad de Sevilla
[7dc06be9]958#@date    2019-01-08
[3673737]959#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
960#@author  Irina Gomez, ETSII Universidad de Sevilla
961#@date    2019-03-05
[9c535e0]962#*/ ##
[ab82469]963
[d2c8674]964function ogGrubInstallPartition ()
965{
[ab82469]966
[9c535e0]967# Variables locales.
[1c69be8]968local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[3f4a9b7]969local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB EFIBOOTDIR
[9c535e0]970
971# Si se solicita, mostrar ayuda.
972if [ "$*" == "help" ]; then
973    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
974           "$FUNCNAME 1 1 FALSE " \
975           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
976    return
977fi 
978
979# Error si no se reciben 2 parámetros.
980[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
981
982DISK=$1; PART=$2;
983CHECKOS=${3:-"FALSE"}
984KERNELPARAM=$4
[1c69be8]985BACKUPNAME=".backup.og"
[9c535e0]986
987#error si no es linux.
988VERSION=$(ogGetOsVersion $DISK $PART)
989echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
990
991#Localizar primera etapa del grub
992FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
993
994#localizar disco segunda etapa del grub
995SECONDSTAGE=$(ogMount $DISK $PART)
996
997#Localizar directorio segunda etapa del grub   
998PREFIXSECONDSTAGE="/boot/grubPARTITION"
999
[39b84ff]1000# Si es EFI instalamos el grub en la ESP
[3f4a9b7]1001EFIOPTGRUB=""
1002# Desde el bootdir uefi y bios buscan el grub.cfg en subdirectorios distintos.
1003EFIBOOTDIR=""
[39b84ff]1004if ogIsEfiActive; then
1005    read EFIDISK EFIPART <<< $(ogGetEsp)
1006    # Comprobamos que exista ESP y el directorio para ubuntu
[e9601e1]1007    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
[67b3142]1008    if [ $? -ne 0 ]; then
1009        ogFormat $EFIDISK $EFIPART FAT32
[e9601e1]1010        EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
1011    fi
[39b84ff]1012    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
[3673737]1013    # Borramos la configuración anterior
1014    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
1015    mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
[3f4a9b7]1016    EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
1017    EFIBOOTDIR="/boot"
[39b84ff]1018fi
1019
[9c535e0]1020# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
[3f4a9b7]1021if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]1022then
[1c69be8]1023        # Si no se reconfigura se utiliza el grub.cfg orginal
1024        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
[67b3142]1025        # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
[1c69be8]1026        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
1027        # Reactivamos el grub con el grub.cfg original.
[67b3142]1028        PREFIXSECONDSTAGE=""
[3f4a9b7]1029else
1030        # SI Reconfigurar segunda etapa (grub.cfg) == TRUE
[40bd9f5]1031
[3f4a9b7]1032        if ogIsEfiActive; then
1033            # UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
1034            if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
1035                 [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
1036            fi
1037        else
1038            #Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
1039            mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
[39b84ff]1040        fi
[9c535e0]1041
[3f4a9b7]1042        #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1043        echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1044        echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1045
1046        #Preparar configuración segunda etapa: crear ubicacion
1047        mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
1048        #Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
1049        sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
[8b5283a]1050        # (ogLive 5.0) Si 'pkgdatadir' está vacía ponemos valor de otros ogLive
1051        sed -i '/grub-mkconfig_lib/i\pkgdatadir=${pkgdatadir:-"${datarootdir}/grub"}' /etc/grub.d/00_header
[3f4a9b7]1052        /etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
1053        #Preparar configuración segunda etapa: crear entrada del sistema operativo
1054        grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
1055
[3673737]1056fi
[67b3142]1057#Instalar el grub
1058grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
1059EVAL=$?
[3673737]1060
[7dc06be9]1061# Movemos el grubx64.efi
[39b84ff]1062if ogIsEfiActive; then
[3f4a9b7]1063    mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
[7dc06be9]1064    rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
[527cd97]1065    cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi
[3f4a9b7]1066    # Nombre OpenGnsys para cargador
[dd890f1]1067    cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi}
[39b84ff]1068fi
[3673737]1069
[3f4a9b7]1070return $EVAL
[ab82469]1071}
1072
[fd0d6e5]1073
[00cede9]1074#/**
[c9c2f1d1]1075#         ogConfigureFstab int_ndisk int_nfilesys
[870619d]1076#@brief   Configura el fstab según particiones existentes
[00cede9]1077#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]1078#@param   int_nfilesys   nº de orden del sistema de archivos
[00cede9]1079#@return  (nada)
1080#@exception OG_ERR_FORMAT    Formato incorrecto.
[c9c2f1d1]1081#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
1082#@warning Puede haber un error si hay más de 1 partición swap.
[870619d]1083#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
1084#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
[c9c2f1d1]1085#@date    2013-03-21
[870619d]1086#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
1087#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1088#@date    2016-11-03
[39b84ff]1089#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
1090#@author  Irina Gómez, ETSII Universidad de Sevilla
1091#@date    2018-12-13
[00cede9]1092#*/ ##
[d2c8674]1093function ogConfigureFstab ()
1094{
[00cede9]1095# Variables locales.
[c9c2f1d1]1096local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
[7dc06be9]1097local EFIDISK EFIPART EFIDEV EFIOPT
[00cede9]1098
1099# Si se solicita, mostrar ayuda.
1100if [ "$*" == "help" ]; then
[c9c2f1d1]1101    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1102           "$FUNCNAME 1 1"
[00cede9]1103    return
1104fi
1105# Error si no se reciben 2 parámetros.
1106[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[c9c2f1d1]1107# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
1108FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
1109[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
1110
1111# Hacer copia de seguridad del fichero fstab original.
1112cp -a ${FSTAB} ${FSTAB}.backup
1113# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
1114DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
1115PARTROOT=$(ogDiskToDev $1 $2)
[200635a]1116# Configuración de swap (solo 1ª partición detectada).
1117PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
[00cede9]1118if [ -n "$PARTSWAP" ]
1119then
[c9c2f1d1]1120    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
1121    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
[00cede9]1122    if [ -n "$DEFSWAP" ]
[c9c2f1d1]1123    then
[870619d]1124        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
[c9c2f1d1]1125        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
[00cede9]1126    else
[870619d]1127        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
[c9c2f1d1]1128        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1129        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
[00cede9]1130    fi 
1131else
[870619d]1132    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
1133    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
[00cede9]1134fi
[39b84ff]1135# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
[47d8ae8]1136if ogIsEfiActive; then
[39b84ff]1137    read EFIDISK EFIPART <<< $(ogGetEsp)
[7dc06be9]1138    EFIDEV=$(ogDiskToDev $EFIDISK $EFIPART)
[9c535e0]1139
[39b84ff]1140    # Opciones de la partición ESP: si no existe ponemos un valor por defecto
[7dc06be9]1141    EFIOPT=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
1142    [ "$EFIOPT" == "" ] && EFIOPT='vfat\tumask=0077\t0\t1'
[c9c2f1d1]1143
[39b84ff]1144    sed -i /"boot\/efi"/d  ${FSTAB}
[7dc06be9]1145    echo -e "$EFIDEV\t/boot/efi\t$EFIOPT" >> ${FSTAB}
[39b84ff]1146fi
1147}
[872b044]1148
[764f50e]1149#/**
[c9c2f1d1]1150#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
[764f50e]1151#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
1152#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]1153#@param   int_nfilesys   nº de orden del sistema de archivos
1154#@param   str_name       nombre asignado (opcional)
[764f50e]1155#@return  (nada)
1156#@exception OG_ERR_FORMAT    Formato incorrecto.
1157#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1158#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[c9c2f1d1]1159#@note    Si no se indica nombre, se asigna un valor por defecto.
1160#@version 1.0.5 - Primera versión para OpenGnSys.
1161#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1162#@date    2013-03-21
[764f50e]1163#*/ ##
1164function ogSetLinuxName ()
1165{
1166# Variables locales.
[c9c2f1d1]1167local MNTDIR ETC NAME
[764f50e]1168
1169# Si se solicita, mostrar ayuda.
1170if [ "$*" == "help" ]; then
[c9c2f1d1]1171    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
1172           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
[764f50e]1173    return
1174fi
[c9c2f1d1]1175# Error si no se reciben 2 o 3 parámetros.
1176case $# in
1177    2)   # Asignar nombre automático (por defecto, "pc").
1178         NAME="$(ogGetHostname)"
1179         NAME=${NAME:-"pc"} ;;
1180    3)   # Asignar nombre del 3er parámetro.
1181         NAME="$3" ;;
1182    *)   # Formato de ejecución incorrecto.
1183         ogRaiseError $OG_ERR_FORMAT
1184         return $?
1185esac
[764f50e]1186
1187# Montar el sistema de archivos.
[5962edd]1188MNTDIR=$(ogMount $1 $2) || return $?
[764f50e]1189
1190ETC=$(ogGetPath $1 $2 /etc)
1191
1192if [ -d "$ETC" ]; then
1193        #cambio de nombre en hostname
[c9c2f1d1]1194        echo "$NAME" > $ETC/hostname
[764f50e]1195        #Opcion A para cambio de nombre en hosts
1196        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
[c9c2f1d1]1197        #Opcion B componer fichero de hosts
1198        cat > $ETC/hosts <<EOF
[764f50e]1199127.0.0.1       localhost
1200127.0.1.1       $NAME
1201
1202# The following lines are desirable for IPv6 capable hosts
1203::1     ip6-localhost ip6-loopback
1204fe00::0 ip6-localnet
1205ff00::0 ip6-mcastprefix
1206ff02::1 ip6-allnodes
1207ff02::2 ip6-allrouters
1208EOF
1209fi
1210}
1211
[df814dd0]1212
[fd0d6e5]1213
[df814dd0]1214#/**
[c9c2f1d1]1215#         ogCleanLinuxDevices int_ndisk int_nfilesys
[df814dd0]1216#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
1217#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]1218#@param   int_nfilesys   nº de orden del sistema de archivos
[df814dd0]1219#@return  (nada)
1220#@exception OG_ERR_FORMAT    Formato incorrecto.
1221#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1222#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[c9c2f1d1]1223#@version 1.0.5 - Primera versión para OpenGnSys.
1224#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1225#@date    2013-03-21
[fd0d6e5]1226#@version 1.0.6b - Elimina fichero resume de hibernacion
1227#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1228#@date    2016-11-07
[df814dd0]1229#*/ ##
1230function ogCleanLinuxDevices ()
1231{
1232# Variables locales.
[c9c2f1d1]1233local MNTDIR
[df814dd0]1234
1235# Si se solicita, mostrar ayuda.
1236if [ "$*" == "help" ]; then
[c9c2f1d1]1237    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1238           "$FUNCNAME 1 1"
[df814dd0]1239    return
1240fi
1241# Error si no se reciben 2 parámetros.
1242[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1243
1244# Montar el sistema de archivos.
[5962edd]1245MNTDIR=$(ogMount $1 $2) || return $?
[df814dd0]1246
[c9c2f1d1]1247# Eliminar fichero de configuración de udev para dispositivos fijos de red.
[fd0d6e5]1248[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
1249# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
1250[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
[df814dd0]1251}
1252
[512c692]1253#/**
[e44e88a]1254# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
[512c692]1255#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1256#@param 1 Numero de disco
1257#@param 2 Numero de particion
[1a2fa9d8]1258#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1259#@param 4 offline  configura el modo offline [offline|online] (opcional)
[512c692]1260#@return  (nada)
1261#@exception OG_ERR_FORMAT    Formato incorrecto.
1262#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1263#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1264# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
[e44e88a]1265#@version 1.0.6 - Prmera integración
1266#@author 
1267#@date    2016-11-07
1268#@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.
1269#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1270#@date    2017-06-17
1271#*/ ##
1272
[512c692]1273
[d2c8674]1274function ogGrubAddOgLive ()
1275{
[1a2fa9d8]1276    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
[512c692]1277
1278    # Si se solicita, mostrar ayuda.
1279    if [ "$*" == "help" ]; then
[1a2fa9d8]1280        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1281                "$FUNCNAME 1 1" \
1282                "$FUNCNAME 1 6 15 offline"
[512c692]1283        return
1284    fi
1285
1286    # Error si no se reciben 2 parámetros.
1287    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
[1a2fa9d8]1288    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
[512c692]1289
1290    # Error si no existe el kernel y el initrd en la cache.
1291    # Falta crear nuevo codigo de error.
[e44e88a]1292    [ -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]1293
1294    # Archivo de configuracion del grub
1295    DIRMOUNT=$(ogMount $1 $2)
1296    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1297
1298    # Error si no existe archivo del grub
1299    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1300
[28ffb59]1301    # Si existe la entrada de opengnsys, se borra
1302    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
[512c692]1303
1304    # Tipo de tabla de particiones
1305    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1306
1307    # Localizacion de la cache
1308    read NUMDISK NUMPART <<< $(ogFindCache)
1309    let NUMDISK=$NUMDISK-1
1310    # kernel y sus opciones. Pasamos a modo usuario
[e44e88a]1311    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
[1a2fa9d8]1312
1313    # Configuracion offline si existe parametro
1314    echo "$@" |grep offline &>/dev/null && STATUS=offline
1315    echo "$@" |grep online  &>/dev/null && STATUS=online
1316    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1317
[512c692]1318    # Numero de línea de la primera entrada del grub.
1319    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1320    # Texto de la entrada de opengnsys
[e44e88a]1321MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
[512c692]1322\tinsmod part_$PARTTABLETYPE \n \
1323\tinsmod ext2 \n \
1324\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1325\tlinux $KERNEL \n \
[e44e88a]1326\tinitrd /boot/${oglivedir}/oginitrd.img \n \
[512c692]1327}"
1328
1329
1330    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1331    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1332
1333    # Ponemos que la entrada por defecto sea la primera.
1334    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1335
1336    # Si me dan valor para timeout lo cambio en el grub.
1337    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1338}
1339
1340#/**
1341# ogGrubHidePartitions num_disk num_part
[872b044]1342#@brief ver ogBootLoaderHidePartitions
[8196942]1343#@see ogBootLoaderHidePartitions
[872b044]1344#*/ ##
[d2c8674]1345function ogGrubHidePartitions ()
1346{
[cade8c0]1347    # Si se solicita, mostrar ayuda.
1348    if [ "$*" == "help" ]; then
[2a44804]1349        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ num_disk_partdata num_partdata ]" \
1350               "$FUNCNAME 1 2" \
1351               "$FUNCNAME 1 2 1 3"
[cade8c0]1352        return
1353    fi
[8196942]1354    ogBootLoaderHidePartitions $@
1355    return $?
1356}
1357
1358#/**
1359# ogBurgHidePartitions num_disk num_part
[872b044]1360#@brief ver ogBootLoaderHidePartitions
[8196942]1361#@see ogBootLoaderHidePartitions
[872b044]1362#*/ ##
[d2c8674]1363function ogBurgHidePartitions ()
1364{
[cade8c0]1365    # Si se solicita, mostrar ayuda.
1366    if [ "$*" == "help" ]; then
[2a44804]1367        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ num_disk_partdata num_partdata ]" \
1368               "$FUNCNAME 1 2" \
1369               "$FUNCNAME 1 2 1 3"
[cade8c0]1370        return
1371    fi
[8196942]1372    ogBootLoaderHidePartitions $@
1373    return $?
1374}
1375
1376#/**
1377# ogBootLoaderHidePartitions num_disk num_part
1378#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
[512c692]1379#@param 1 Numero de disco
1380#@param 2 Numero de particion
[7208cc9]1381#@param 3 Numero de disco de la partición de datos (no ocultar)
1382#@param 4 Numero de particion de datos (no ocultar)
[512c692]1383#@return  (nada)
1384#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]1385#@exception No existe archivo de configuracion del grub/burg.
[e9c3156]1386#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1387#@author  Irina Gomez, ETSII Universidad de Sevilla
1388#@date    2015-11-17
[8196942]1389#@version 1.1 Se generaliza la función para grub y burg
1390#@author  Irina Gomez, ETSII Universidad de Sevilla
1391#@date    2017-10-20
[872b044]1392#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1393#@author  Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
1394#@date    2018-07-05
[7208cc9]1395#@version Se permite una partición de datos que no se ocultará. Soporta más de un disco. Compatible con grub.cfg creado por ogLive 5.0
1396#@author  Irina Gomez, ETSII Universidad de Sevilla
1397#@date    2019-08-26
[512c692]1398#*/
[872b044]1399
[d2c8674]1400function ogBootLoaderHidePartitions ()
1401{
[7208cc9]1402    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY WINPART ENTRY LINE PART PARTDATA TEXT PARTHIDDEN HIDDEN
[8196942]1403
[512c692]1404    # Si se solicita, mostrar ayuda.
1405    if [ "$*" == "help" ]; then
[7208cc9]1406        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
[512c692]1407        return
1408    fi
1409
[cade8c0]1410    # Nombre de la función que llama a esta.
1411    FUNC="${FUNCNAME[@]:1}"
1412    FUNC="${FUNC%%\ *}"
1413
[512c692]1414    # Error si no se reciben 2 parámetros.
[7208cc9]1415    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ num_disk_partdata num_partdata ]"; echo $?)
1416    # Si no existe $4 pongo un valor imposible para la partición de datos
1417    [ $# -eq 4 ] && PARTDATA=$(ogDiskToDev $3 $4) || PARTDATA=0
[512c692]1418
1419    # Archivo de configuracion del grub
1420    DIRMOUNT=$(ogMount $1 $2)
[2a44804]1421    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
[8196942]1422    case "$FUNC" in
1423        ogGrubHidePartitions)
1424            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1425            ;;
1426        ogBurgHidePartitions)
1427            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1428            ;;
1429        *)
[2a44804]1430            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
[8196942]1431            return $?
1432            ;;
1433    esac
[512c692]1434
1435    # Error si no existe archivo del grub
[8196942]1436    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
[512c692]1437
[e9c3156]1438    # Si solo hay una particion de Windows me salgo
[7208cc9]1439    [ $(fdisk -l $(ogDiskToDev) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
[512c692]1440
1441    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
[8196942]1442    sed -i '/parttool/d' $CFGFILE
[512c692]1443
1444    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
[7208cc9]1445
[872b044]1446#   /*  (comentario de bloque para  Doxygen)
[512c692]1447    # Entradas de Windows: numero de linea y particion. De mayor a menor.
[7208cc9]1448    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  gsub(/^.*dev/,"");  print NR":/dev"$1} ' $CFGFILE | sed -e '1!G;h;$!d')
[872b044]1449    #*/ (comentario para bloque Doxygen)
[e9c3156]1450    # Particiones de Windows, pueden no estar en el grub.
[7208cc9]1451    WINPART=$(fdisk -l $(ogDiskToDev)|awk '/NTFS/ {print $1}'|sed '1!G;h;$!d')
1452
1453
[512c692]1454    # Modifico todas las entradas de Windows.
1455    for ENTRY in $WINENTRY; do
1456        LINE=${ENTRY%:*}
[7208cc9]1457        PART=${ENTRY#*:}
1458
[512c692]1459        # En cada entrada, oculto o muestro cada particion.
1460        TEXT=""
[7208cc9]1461        for PARTHIDDEN in $WINPART; do
1462                # Muestro la particion de la entrada actual y la de datos.
1463                [ "$PARTHIDDEN" == "$PART" -o "$PARTHIDDEN" == "$PARTDATA" ] && HIDDEN="-" || HIDDEN="+"
1464                read NUMDISK NUMPART <<< $(ogDevToDisk $PARTHIDDEN)
[512c692]1465
[7208cc9]1466                TEXT="\tparttool (hd$((NUMDISK-1)),$PARTTABLETYPE$NUMPART) hidden$HIDDEN \n$TEXT"
[512c692]1467        done
[7208cc9]1468
[8196942]1469        sed -i "${LINE}a\ $TEXT" $CFGFILE
[512c692]1470    done
1471
1472    # Activamos la particion que se inicia en todas las entradas de windows.
[8196942]1473    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
[512c692]1474}
1475
1476#/**
[be87371]1477# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
[872b044]1478#@brief ver ogBootLoaderDeleteEntry
1479#@see ogBootLoaderDeleteEntry
[8196942]1480#*/
[d2c8674]1481function ogGrubDeleteEntry ()
1482{
[cade8c0]1483    # Si se solicita, mostrar ayuda.
1484    if [ "$*" == "help" ]; then
[be87371]1485        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1486                "$FUNCNAME 1 6 2 1"
[cade8c0]1487        return
1488    fi
[8196942]1489    ogBootLoaderDeleteEntry $@
1490    return $?
1491}
1492
1493#/**
[be87371]1494# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
[872b044]1495#@brief ver ogBootLoaderDeleteEntry
[8196942]1496#@see ogBootLoaderDeleteEntry
1497#*/
[d2c8674]1498function ogBurgDeleteEntry ()
1499{
[cade8c0]1500    # Si se solicita, mostrar ayuda.
1501    if [ "$*" == "help" ]; then
[be87371]1502        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1503                "$FUNCNAME 1 6 2 1"
[cade8c0]1504        return
1505    fi
[8196942]1506    ogBootLoaderDeleteEntry $@
1507    return $?
1508}
1509
1510#/**
[da53464]1511# ogRefindDeleteEntry num_disk_delete num_part_delete
1512#@brief ver ogBootLoaderDeleteEntry
1513#@see ogBootLoaderDeleteEntry
1514#*/
1515function ogRefindDeleteEntry ()
1516{
1517    local EFIDISK EFIPART
1518    # Si se solicita, mostrar ayuda.
1519    if [ "$*" == "help" ]; then
1520        ogHelp  "$FUNCNAME" "$FUNCNAME int_disk_delete int_npartition_delete" \
1521                "$FUNCNAME 2 1"
1522        return
1523    fi
1524    read EFIDISK EFIPART <<< $(ogGetEsp)
1525    ogBootLoaderDeleteEntry $EFIDISK $EFIPART $@
1526    return $?
1527}
1528
1529#/**
[8196942]1530# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
[512c692]1531#@brief Borra en el grub las entradas para el inicio en una particion.
1532#@param 1 Numero de disco donde esta el grub
1533#@param 2 Numero de particion donde esta el grub
[be87371]1534#@param 3 Numero del disco del que borramos las entradas
1535#@param 4 Numero de la particion de la que borramos las entradas
[da53464]1536#@note Tiene que ser llamada desde ogGrubDeleteEntry, ogBurgDeleteEntry o ogRefindDeleteEntry
[512c692]1537#@return  (nada)
[8196942]1538#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
[512c692]1539#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]1540#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1541#@version 1.1 Se generaliza la función para grub y burg
1542#@author  Irina Gomez, ETSII Universidad de Sevilla
1543#@date    2017-10-20
[872b044]1544#*/ ##
1545
[d2c8674]1546function ogBootLoaderDeleteEntry ()
1547{
[da53464]1548    local FUNC DIRMOUNT CFGFILE LABEL MENUENTRY DELETEENTRY ENDENTRY ENTRY
[512c692]1549
[cade8c0]1550    # Si se solicita, mostrar ayuda.
1551    if [ "$*" == "help" ]; then
[da53464]1552        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry, ogGrubDeleteEntry or ogRefindDeleteEntry"
[cade8c0]1553        return
1554    fi
1555
[be87371]1556    # Si el número de parámetros menos que 4 nos salimos
1557    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1558 
1559
[8196942]1560    # Nombre de la función que llama a esta.
1561    FUNC="${FUNCNAME[@]:1}"
1562    FUNC="${FUNC%%\ *}"
[512c692]1563
[8196942]1564    # Archivo de configuracion del grub
1565    DIRMOUNT=$(ogMount $1 $2)
[da53464]1566    # La función debe ser llamanda desde ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry.
[8196942]1567    case "$FUNC" in
1568        ogGrubDeleteEntry)
1569            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1570            ;;
1571        ogBurgDeleteEntry)
1572            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1573            ;;
[da53464]1574        ogRefindDeleteEntry)
1575            CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
1576            ;;
[8196942]1577        *)
[da53464]1578            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry."
[8196942]1579            return $?
1580            ;;
1581    esac
[512c692]1582
[8196942]1583    # Dispositivo
[da53464]1584    if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1585        LABEL=$(printf "Part-%02d-%02d" $3 $4)
1586    else
1587        LABEL=$(ogDiskToDev $3 $4)
1588    fi
[512c692]1589
[da53464]1590    # Error si no existe archivo de configuración
[be87371]1591    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
[512c692]1592
[be87371]1593    # Numero de linea de cada entrada.
1594    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
[512c692]1595
1596    # Entradas que hay que borrar.
[da53464]1597    DELETEENTRY=$(grep -n menuentry.*$LABEL $CFGFILE| cut -d: -f1)
[8196942]1598
1599    # Si no hay entradas para borrar me salgo con aviso
[da53464]1600    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $LABEL" || return $?
[512c692]1601
1602    # Recorremos el fichero del final hacia el principio.
[8196942]1603    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
[512c692]1604    for ENTRY in $MENUENTRY; do
1605        # Comprobamos si hay que borrar la entrada.
1606        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1607            let ENDENTRY=$ENDENTRY-1
[8196942]1608            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
[512c692]1609        fi
1610
1611        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1612        ENDENTRY=$ENTRY
1613    done
1614}
1615
[872b044]1616#/**
[74e01a7]1617#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1618#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1619#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1620#@param   int_disk_SecondStage     
1621#@param   int_part_SecondStage     
1622#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1623#@return 
1624#@exception OG_ERR_FORMAT    Formato incorrecto.
[c0fde6d]1625#@exception OG_ERR_PARTITION  Partición no soportada
[74e01a7]1626#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1627#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1628#@date    2017-06-23
[19c9dca]1629#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1630#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1631#@date    2018-01-21
[deacf00]1632#@version 1.1.0 - Refactorizar fichero de configuacion
1633#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1634#@date    2018-01-24
[872b044]1635#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1636#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1637#@date    2018-07-05
[74e01a7]1638#*/ ##
1639
[d2c8674]1640function ogBurgInstallMbr ()
1641{
[74e01a7]1642 
1643# Variables locales.
[20c4441]1644local BINARYAVAILABLE PART DISK DEVICE MOUNTDISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
[74e01a7]1645
1646# Si se solicita, mostrar ayuda.
1647if [ "$*" == "help" ]; then
1648    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1649           "$FUNCNAME 1 1 FALSE " \
1650           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1651    return
1652fi 
1653
1654# Error si no se reciben 2 parametros.
1655[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1656
[0be2014]1657#Error si no tenemos el binario burg
1658BINARYAVAILABLE=$(burg-install  -v &>/dev/null && echo "YES" ||echo "NO")
1659if [ "$BINARYAVAILABLE" == NO ]; then
1660    if [ -e $OGLIB/burg/burg.tgz ]; then
1661        cd / ; tar xzvf $OGLIB/burg/burg.tgz --strip 1 &>/dev/null
1662    else
1663        return $(ogRaiseError $OG_ERR_NOTEXEC "Binary burg not found"; echo $?)
1664    fi
1665fi
[74e01a7]1666
1667DISK=$1; PART=$2;
1668CHECKOS=${3:-"FALSE"}
1669KERNELPARAM=$4
1670BACKUPNAME=".backup.og"
1671
[20c4441]1672#Controlar disco no uefi
1673ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?)
1674#Controlar particionado tipo msdos
1675ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?)
1676#Controlar existencia de disco y particion
1677DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $?
1678MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $?
1679#Controlar particion segunda etapa del burg
1680ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg.cfg soporta solo particiones linux"; echo $?)
1681#Controlar acceso de escritura a la particion segunda etapa del burg
1682ogIsReadonly $DISK $PART &&  return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?)
1683
1684#Asigar la primera etapa del grub en el primer disco duro
[74e01a7]1685FIRSTSTAGE=$(ogDiskToDev 1)
[20c4441]1686#Localizar disco segunda etapa del grub
[74e01a7]1687SECONDSTAGE=$(ogMount $DISK $PART)
1688
[20c4441]1689#Preparar el directorio principal de la segunda etapa (y copia los binarios)
[0be2014]1690[ -d ${SECONDSTAGE}/boot/burg/ ]  || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/*  ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/themes  ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; #*/ ## (comentario Dogygen) #*/ ## (comentario Dogygen)
[20c4441]1691#Copiar el tema de opengnsys
[74e01a7]1692mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
[19c9dca]1693cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
[74e01a7]1694
[20c4441]1695# No configurar la segunda etapa (grub.cfg). Parámetro FALSE
[0be2014]1696if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ];
[74e01a7]1697then
1698    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1699    then
[19c9dca]1700        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]1701        return $?
1702    fi
1703fi
1704
[20c4441]1705# Configurrar la segunda etapa (burg.cfg) == tercer parámetro TRUE
[74e01a7]1706
[20c4441]1707#llamar a updateBootCache para que aloje la primera fase del ogLive
[74e01a7]1708updateBootCache
1709
1710#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1711echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1712echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1713
1714#Preparar configuración segunda etapa: crear ubicacion
1715mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1716#Preparar configuración segunda etapa: crear cabecera del fichero
1717FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
[872b044]1718#/* ## (comentario Dogygen)
[74e01a7]1719cat > "$FILECFG" << EOF
1720
1721set theme_name=OpenGnsys
1722set gfxmode=1024x768
[deacf00]1723
[74e01a7]1724
1725set locale_dir=(\$root)/boot/burg/locale
1726
1727set default=0
1728set timeout=25
1729set lang=es
1730
1731
1732insmod ext2
1733insmod gettext
1734
1735
[deacf00]1736
1737
[74e01a7]1738if [ -s \$prefix/burgenv ]; then
1739  load_env
1740fi
1741
[deacf00]1742
1743
[74e01a7]1744if [ \${prev_saved_entry} ]; then
1745  set saved_entry=\${prev_saved_entry}
1746  save_env saved_entry
1747  set prev_saved_entry=
1748  save_env prev_saved_entry
1749  set boot_once=true
1750fi
1751
1752function savedefault {
1753  if [ -z \${boot_once} ]; then
1754    saved_entry=\${chosen}
1755    save_env saved_entry
1756  fi
1757}
1758function select_menu {
1759  if menu_popup -t template_popup theme_menu ; then
1760    free_config template_popup template_subitem menu class screen
1761    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1762    save_env theme_name
1763    menu_refresh
1764  fi
1765}
1766
1767function toggle_fold {
1768  if test -z $theme_fold ; then
1769    set theme_fold=1
1770  else
1771    set theme_fold=
1772  fi
1773  save_env theme_fold
1774  menu_refresh
1775}
1776function select_resolution {
1777  if menu_popup -t template_popup resolution_menu ; then
1778    menu_reload_mode
1779    save_env gfxmode
1780  fi
1781}
1782
1783
1784if test -f \${prefix}/themes/\${theme_name}/theme ; then
1785  insmod coreui
1786  menu_region.text
1787  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
[deacf00]1788  load_config \${prefix}/themes/conf.d/10_hotkey   
[74e01a7]1789  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1790  insmod vbe
1791  insmod png
1792  insmod jpeg
1793  set gfxfont="Unifont Regular 16"
1794  menu_region.gfx
1795  vmenu resolution_menu
1796  controller.ext
1797fi
1798
1799
1800EOF
[872b044]1801#*/ ## (comentario Dogygen)
[74e01a7]1802
1803#Preparar configuración segunda etapa: crear entrada del sistema operativo
1804grubSyntax "$KERNELPARAM" >> "$FILECFG"
1805#Instalar el burg
[19c9dca]1806burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]1807}
1808
[0d2e65b]1809#/**
[be87371]1810# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
[872b044]1811#@brief ver ogBootLoaderDefaultEntry
[be87371]1812#@see ogBootLoaderDefaultEntry
[872b044]1813#*/ ##
[d2c8674]1814function ogGrubDefaultEntry ()
1815{
[be87371]1816    # Si se solicita, mostrar ayuda.
1817    if [ "$*" == "help" ]; then
1818        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1819               "$FUNCNAME 1 6 1 1"
1820        return
1821    fi
1822    ogBootLoaderDefaultEntry $@
1823    return $?
1824}
1825
1826#/**
1827# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
[872b044]1828#@brief ver ogBootLoaderDefaultEntry
[be87371]1829#@see ogBootLoaderDefaultEntry
[872b044]1830#*/ ##
[d2c8674]1831function ogBurgDefaultEntry ()
1832{
[be87371]1833    # Si se solicita, mostrar ayuda.
1834    if [ "$*" == "help" ]; then
1835        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1836               "$FUNCNAME 1 6 1 1"
1837        return
1838    fi
1839    ogBootLoaderDefaultEntry $@
1840    return $?
1841}
1842
[da53464]1843
1844#/**
1845# ogRefindDefaultEntry int_disk_default_entry int_npartition_default_entry
1846#@brief ver ogBootLoaderDefaultEntry
1847#@see ogBootLoaderDefaultEntry
1848#*/ ##
1849function ogRefindDefaultEntry ()
1850{
1851    local EFIDISK EFIPART
1852    # Si se solicita, mostrar ayuda.
1853    if [ "$*" == "help" ]; then
1854        ogHelp "$FUNCNAME" "$FUNCNAME int_disk_default_entry int_npartition_default_entry" \
1855               "$FUNCNAME 1 1"
1856        return
1857    fi
1858
1859    read EFIDISK EFIPART <<< $(ogGetEsp)
1860    ogBootLoaderDefaultEntry $EFIDISK $EFIPART $@
1861    return $?
1862}
1863
[be87371]1864#/**
1865# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
[0d2e65b]1866#@brief   Configura la entrada por defecto de Burg
1867#@param   int_disk_SecondStage     
1868#@param   int_part_SecondStage     
[be87371]1869#@param   int_disk_default_entry
1870#@param   int_part_default_entry
[0d2e65b]1871#@return 
1872#@exception OG_ERR_FORMAT    Formato incorrecto.
1873#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1874#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1875#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
[be87371]1876#@version 1.1.0 - Define la entrada por defecto del Burg
[0d2e65b]1877#@author  Irina Gomez, ETSII Universidad de Sevilla
1878#@date    2017-08-09
[be87371]1879#@version 1.1 Se generaliza la función para grub y burg
1880#@author  Irina Gomez, ETSII Universidad de Sevilla
1881#@date    2018-01-04
[0d2e65b]1882#*/ ##
[d2c8674]1883function ogBootLoaderDefaultEntry ()
1884{
[0d2e65b]1885
1886# Variables locales.
[da53464]1887local PART FUNC DIRMOUNT LABEL CFGFILE DEFAULTENTRY MENUENTRY MSG
[0d2e65b]1888
1889# Si se solicita, mostrar ayuda.
1890if [ "$*" == "help" ]; then
[da53464]1891    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
[0d2e65b]1892    return
1893fi 
1894
[be87371]1895# Nombre de la función que llama a esta.
1896FUNC="${FUNCNAME[@]:1}"
1897FUNC="${FUNC%%\ *}"
1898
[0d2e65b]1899# Error si no se reciben 3 parametros.
[be87371]1900[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
[0d2e65b]1901
1902# Error si no puede montar sistema de archivos.
[be87371]1903DIRMOUNT=$(ogMount $1 $2) || return $?
1904
1905# Comprobamos que exista fichero de configuración
[da53464]1906# La función debe ser llamanda desde ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry.
[be87371]1907case "$FUNC" in
1908    ogGrubDefaultEntry)
1909        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1910        ;;
1911    ogBurgDefaultEntry)
1912        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1913        ;;
[da53464]1914    ogRefindDefaultEntry)
1915        CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
1916        ;;
[be87371]1917    *)
[da53464]1918        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
[be87371]1919        return $?
1920        ;;
1921esac
1922
1923# Error si no existe archivo de configuración
1924[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1925
1926# Dispositivo
[da53464]1927if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1928    LABEL=$(printf "Part-%02d-%02d" $3 $4)
1929else
1930    LABEL=$(ogDiskToDev $3 $4)
1931fi
[0d2e65b]1932
[be87371]1933# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
[da53464]1934DEFAULTENTRY=$(grep -n -m 1 menuentry.*$LABEL $CFGFILE| cut -d: -f1)
[0d2e65b]1935
[be87371]1936# Si no hay entradas para borrar me salgo con aviso
[da53464]1937[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $LABEL" || return $?
[0d2e65b]1938
[be87371]1939# Número de la de linea por defecto en el menú de usuario
1940MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
[da53464]1941
1942if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
1943    sed -i /default_selection.*$/d $CFGFILE
1944    sed -i "1 i\default_selection $MENUENTRY" $CFGFILE
1945else
1946    # En grub y burg las líneas empiezan a contar desde cero
1947    let MENUENTRY=$MENUENTRY-1
[037fc85]1948    sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?$"/"set default=\"$MENUENTRY\""/g $CFGFILE
[da53464]1949fi
[be87371]1950MSG="MSG_HELP_$FUNC"
1951echo "${!MSG%%\.}: $@"
[0d2e65b]1952}
1953
1954#/**
[be87371]1955# ogGrubOgliveDefaultEntry num_disk num_part
[872b044]1956#@brief ver ogBootLoaderOgliveDefaultEntry
[be87371]1957#@see ogBootLoaderOgliveDefaultEntry
[872b044]1958#*/ ##
[d2c8674]1959function ogGrubOgliveDefaultEntry ()
1960{
[be87371]1961    # Si se solicita, mostrar ayuda.
1962    if [ "$*" == "help" ]; then
1963        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1964               "$FUNCNAME 1 6"
1965        return
1966    fi
1967    ogBootLoaderOgliveDefaultEntry $@
1968    return $?
1969}
1970
1971#/**
1972# ogBurgOgliveDefaultEntry num_disk num_part
[872b044]1973#@brief ver ogBootLoaderOgliveDefaultEntry
[be87371]1974#@see ogBootLoaderOgliveDefaultEntry
[872b044]1975#*/ ##
[d2c8674]1976function ogBurgOgliveDefaultEntry ()
1977{
[be87371]1978    # Si se solicita, mostrar ayuda.
1979    if [ "$*" == "help" ]; then
1980        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1981               "$FUNCNAME 1 6"
1982        return
1983    fi
1984    ogBootLoaderOgliveDefaultEntry $@
1985    return $?
1986}
1987
[da53464]1988
1989#/**
1990# ogRefindOgliveDefaultEntry
1991#@brief ver ogBootLoaderOgliveDefaultEntry
1992#@see ogBootLoaderOgliveDefaultEntry
1993#*/ ##
1994function ogRefindOgliveDefaultEntry ()
1995{
1996    local EFIDISK EFIPART
1997    # Si se solicita, mostrar ayuda.
1998    if [ "$*" == "help" ]; then
1999        ogHelp "$FUNCNAME" "$FUNCNAME" \
2000               "$FUNCNAME"
2001        return
2002    fi
2003
2004    read EFIDISK EFIPART <<< $(ogGetEsp)
2005    ogBootLoaderOgliveDefaultEntry $EFIDISK $EFIPART
2006    return $?
2007}
2008
2009
[be87371]2010#/**
2011# ogBootLoaderOgliveDefaultEntry
[0d2e65b]2012#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
2013#@param   int_disk_SecondStage     
2014#@param   int_part_SecondStage     
2015#@return 
2016#@exception OG_ERR_FORMAT    Formato incorrecto.
2017#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2018#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
2019#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
2020#@version 1.1.0 - Primeras pruebas con Burg
2021#@author  Irina Gomez, ETSII Universidad de Sevilla
2022#@date    2017-08-09
[be87371]2023#@version 1.1 Se generaliza la función para grub y burg
2024#@author  Irina Gomez, ETSII Universidad de Sevilla
2025#@date    2018-01-04
[0d2e65b]2026#*/ ##
[d2c8674]2027function  ogBootLoaderOgliveDefaultEntry ()
2028{
[0d2e65b]2029
2030# Variables locales.
[be87371]2031local FUNC PART CFGFILE NUMENTRY MSG
[0d2e65b]2032
2033# Si se solicita, mostrar ayuda.
2034if [ "$*" == "help" ]; then
[da53464]2035    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry" \
[0d2e65b]2036    return
2037fi 
2038
[be87371]2039# Nombre de la función que llama a esta.
2040FUNC="${FUNCNAME[@]:1}"
2041FUNC="${FUNC%%\ *}"
2042
[0d2e65b]2043# Error si no se reciben 2 parametros.
2044[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
2045
2046# Error si no puede montar sistema de archivos.
2047PART=$(ogMount $1 $2) || return $?
[da53464]2048# La función debe ser llamanda desde ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry.
[be87371]2049case "$FUNC" in
2050    ogGrubOgliveDefaultEntry)
2051        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
2052        ;;
2053    ogBurgOgliveDefaultEntry)
2054        CFGFILE="$PART/boot/burg/burg.cfg"
2055        ;;
[da53464]2056    ogRefindOgliveDefaultEntry)
2057        CFGFILE="$PART/EFI/refind/refind.conf"
2058        ;;
[be87371]2059    *)
[da53464]2060        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry."
[be87371]2061        return $?
2062        ;;
2063esac
[0d2e65b]2064
[be87371]2065# Comprobamos que exista fichero de configuración
2066[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
[0d2e65b]2067
2068# Detectamos cual es la entrada de ogLive
[be87371]2069NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
[0d2e65b]2070
2071# Si no existe entrada de ogLive nos salimos
[be87371]2072[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
[0d2e65b]2073
[da53464]2074if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
2075    sed -i /default_selection.*$/d $CFGFILE
2076
2077    sed -i "1 i\default_selection $NUMENTRY" $CFGFILE
2078else
2079    let NUMENTRY=$NUMENTRY-1
2080    sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
2081fi
[0d2e65b]2082
[be87371]2083MSG="MSG_HELP_$FUNC"
2084echo "${!MSG%%\.}: $@"
[0d2e65b]2085}
[74e01a7]2086
[deacf00]2087
2088#/**
[4389dcc5]2089#         ogGrubSecurity int_disk_GRUBCFG int_partition_GRUBCFG [user] [password]
[d6a0084]2090#@brief   Configura grub.cfg para que sólo permita editar entrada o acceder a línea de comandos al usuario especificado
2091#@param   int_disk_SecondStage
2092#@param   int_part_SecondStage
2093#@param   user (default root)
2094#@param   password (default "", no puede entrar)
2095#@return  (nada)
2096#@exception OG_ERR_FORMAT    Formato incorrecto.
2097#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar (ogMount).
2098#@exception OG_ERR_NOTFOUND  No encuentra archivo de configuración del grub.
2099#@author  Irina Gomez, ETSII Universidad de Sevilla
2100#@date    2019-12-17
2101#*/ ##
2102function ogGrubSecurity ()
2103{
2104# Variables locales.
[4389dcc5]2105local SECONDSTAGE GRUBGFC FILE USER PASSWD ENCRYPTPASSWD
[d6a0084]2106
2107# Si se solicita, mostrar ayuda.
2108if [ "$*" == "help" ]; then
[4389dcc5]2109    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage  [USER] [PASSWORD]" \
2110           "$FUNCNAME 1 1 " \
2111           "$FUNCNAME 1 2 user clave"
[d6a0084]2112    return
2113fi
2114
[4389dcc5]2115# Error si no se reciben 2 parámetros.
2116[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [USER] [PASSWORD]"|| return  $?
[d6a0084]2117
2118#localizar disco segunda etapa del grub
2119SECONDSTAGE=$(ogMount "$1" "$2") || return $?
2120
[4389dcc5]2121GRUBGFC=$(ls $SECONDSTAGE/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg,grub.cfg.backup.og} 2>/dev/null)
[d6a0084]2122
2123# comprobamos que exista el archivo de configuración.
[4389dcc5]2124[ -n "$GRUBGFC" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
[d6a0084]2125
[4389dcc5]2126USER=${3:-root}
2127PASSWD=${4:-""}
[d6a0084]2128
2129ENCRYPTPASSWD=$(echo -e "$PASSWD\n$PASSWD"|grub-mkpasswd-pbkdf2|sed -e 1,2d -e s/^.*grub/grub/)
2130
[4389dcc5]2131for FILE in $GRUBGFC; do
2132    # Eliminamos configuración anterior
2133    sed -i -e /superusers/d -e /password_pbkdf2/d $FILE
[d6a0084]2134
[4389dcc5]2135    # Configuramos grub.cfg para que sólo permita editar o entrar en línea de comandos al usuario especificado
2136    [ "$PASSWD" == "" ] || sed -i "1i\password_pbkdf2 $USER $ENCRYPTPASSWD" $FILE
2137    sed -i "1i\set superusers=\"$USER\"" $FILE
[d6a0084]2138
[4389dcc5]2139    # Permitimos que se seleccionen las entradas
2140    sed -i /"menuentry "/s/"{"/"--unrestricted {"/ $FILE
2141done
[d6a0084]2142}
2143
2144
2145#/**
[deacf00]2146# ogGrubSetTheme num_disk num_part str_theme
[872b044]2147#@brief ver ogBootLoaderSetTheme
[deacf00]2148#@see ogBootLoaderSetTheme
[872b044]2149#*/ ##
[d2c8674]2150function ogGrubSetTheme ()
2151{
[deacf00]2152    # Si se solicita, mostrar ayuda.
2153    if [ "$*" == "help" ]; then
2154        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
2155               "$FUNCNAME 1 4 ThemeBasic"\
2156               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2157        return
2158    fi
2159    ogBootLoaderSetTheme $@
2160    return $?
2161}
2162
2163#/**
2164# ogBurgSetTheme num_disk num_part str_theme
[872b044]2165#@brief ver ogBootLoaderSetTheme
[deacf00]2166#@see ogBootLoaderSetTheme
[872b044]2167#*/ ##
[d2c8674]2168function ogBurgSetTheme  ()
2169{
[deacf00]2170    # Si se solicita, mostrar ayuda.
2171    if [ "$*" == "help" ]; then
2172        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
2173               "$FUNCNAME 1 4 ThemeBasic" \
2174               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2175        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
2176               
2177        return
2178    fi
2179    ogBootLoaderSetTheme $@
2180    return $?
2181}
2182
2183
[17e90bd]2184#/**
[da53464]2185# ogRefindSetTheme str_theme
[17e90bd]2186#@brief ver ogBootLoaderSetTheme
2187#@see ogBootLoaderSetTheme
2188#*/ ##
2189function ogRefindSetTheme () {
2190    local PART DIRTHEME CFGFILE
2191    # Si se solicita, mostrar ayuda.
2192    if [ "$*" == "help" ]; then
[da53464]2193        ogHelp "$FUNCNAME" "$FUNCNAME str_themeName" \
2194               "$FUNCNAME ThemeBasic"
2195        echo -e "\nThemes in $OGLIB/refind:\n$(ls $OGLIB/refind/themes/ 2>/dev/null)"
[17e90bd]2196
2197        return
2198    fi
2199
[da53464]2200    # Detectamos partición ESP
2201    read EFIDISK EFIPART <<< $(ogGetEsp)
2202
2203    PART=$(ogMount $EFIDISK $EFIPART) || return $?
[17e90bd]2204    DIRTHEME="$PART/EFI/refind/themes"
2205    CFGFILE="$PART/EFI/refind/refind.conf"
2206
2207    # Para utilizar ogBootLoaderSetTheme es necesario la entrada set theme_name
2208    if [ -f $CFGFILE ]; then
[da53464]2209        sed -i '1 i\set theme_name=none' $CFGFILE
[17e90bd]2210    else
2211        ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2212    fi
2213    # Creamos el directorio para los temas
2214    [ -d $DIRTHEME ] || mkdir $DIRTHEME
2215
[da53464]2216    ogBootLoaderSetTheme $EFIDISK $EFIPART $@
[17e90bd]2217    return $?
2218}
2219
[deacf00]2220
2221#/**
2222# ogBootLoaderSetTheme
2223#@brief   asigna un tema al BURG
2224#@param   int_disk_SecondStage     
2225#@param   int_part_SecondStage 
2226#@param   str_theme_name   
2227#@return 
2228#@exception OG_ERR_FORMAT    Formato incorrecto.
2229#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
[17e90bd]2230#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg refind.conf.
[deacf00]2231#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
[17e90bd]2232#@exception OG_ERR_NOTFOUND  Fichero de configuración del tema no encontrado: theme.conf (sólo refind).
2233#@note    El tema debe situarse en OGLIB/BOOTLOADER/themes
[deacf00]2234#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2235#@author  Antonio J. Doblas Viso. Universidad de Malaga
2236#@date    2018-01-24
[17e90bd]2237#@version 1.1.1 - Soporta rEFInd (ticket #802 #888).
2238#@author  Irina Gomez. Universidad de Sevilla
2239#@date    2019-03-22
[deacf00]2240#*/ ##
[d2c8674]2241function  ogBootLoaderSetTheme ()
2242{
[deacf00]2243
2244# Variables locales.
[17e90bd]2245local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG NEWTHEMECFG
[deacf00]2246
2247# Si se solicita, mostrar ayuda.
2248if [ "$*" == "help" ]; then
[da53464]2249    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
[deacf00]2250    return   
2251fi
2252 
2253
2254NEWTHEME="$3"
2255
2256# Nombre de la función que llama a esta.
2257FUNC="${FUNCNAME[@]:1}"
2258FUNC="${FUNC%%\ *}"
2259
2260
2261
[17e90bd]2262# Error si no se reciben 3 parametros.
[deacf00]2263[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
2264
2265# Error si no puede montar sistema de archivos.
2266PART=$(ogMount $1 $2) || return $?
[da53464]2267# La función debe ser llamanda desde ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme.
[deacf00]2268case "$FUNC" in
2269    ogGrubSetTheme)
[da53464]2270        BOOTLOADER="grub"
[17e90bd]2271        BOOTLOADERDIR="boot/grubMBR"
[deacf00]2272        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2273        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
2274        return $?               
2275        ;;
2276    ogBurgSetTheme)
2277        BOOTLOADER="burg"
[17e90bd]2278        BOOTLOADERDIR="boot/burg"
[deacf00]2279        CFGFILE="$PART/boot/burg/burg.cfg"       
2280        ;;
[17e90bd]2281    ogRefindSetTheme)
2282        BOOTLOADER="refind"
2283        BOOTLOADERDIR="EFI/refind"
2284        CFGFILE="$PART/EFI/refind/refind.conf"
2285        ;;
[deacf00]2286    *)
[17e90bd]2287        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
[deacf00]2288        return $?
2289        ;;
2290esac
2291
2292# Comprobamos que exista fichero de configuración
2293[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2294
2295# Detectamos cual es el tema asignado
2296THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
2297# Si no existe entrada de theme_name  nos salimos
2298[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
2299
2300#Actualizamos el tema del servidor a la particion
2301if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
[17e90bd]2302        # Para refind es necesario que exista theme.conf en el directorio del tema.
2303        if [ "$BOOTLOADER" == "refind" ]; then
2304            NEWTHEMECFG="$OGLIB/$BOOTLOADER/themes/$NEWTHEME/theme.conf"
2305            [ -f $NEWTHEMECFG ] || ogRaiserError $OG_ERR_NOTFOUND "theme.conf" || return $?
2306            grep -v "^#" $NEWTHEMECFG >> $CFGFILE
[ed4b2fe]2307            # eliminamos "set theme" es de grub y no de refind
2308            sed -i '/theme_name/d' $CFGFILE
[17e90bd]2309        fi
2310        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/$BOOTLOADERDIR/themes/
[deacf00]2311fi
2312
2313#Verificamos que el tema esta en la particion
[17e90bd]2314if ! [ -d $PART/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
2315                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/$BOOTLOADERDIR/themes/" || return $?
[deacf00]2316fi
2317
2318#Cambiamos la entrada el fichero de configuración.
[ed4b2fe]2319sed --regexp-extended -i  s/"set theme_name=$THEME"/"set theme_name=$NEWTHEME"/g $CFGFILE
[deacf00]2320
2321
2322}
2323
2324#/**
2325# ogGrubSetAdminKeys num_disk num_part str_theme
[872b044]2326#@brief ver ogBootLoaderSetTheme
[deacf00]2327#@see ogBootLoaderSetTheme
[872b044]2328#*/ ##
[d2c8674]2329function ogGrubSetAdminKeys ()
2330{
[deacf00]2331    # Si se solicita, mostrar ayuda.
2332    if [ "$*" == "help" ]; then
2333        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2334               "$FUNCNAME 1 4 FALSE "\
2335               "$FUNCNAME \$(ogFindCache) ThemeBasic"
2336        return
2337    fi
2338    ogBootLoaderSetAdminKeys $@
2339    return $?
2340}
2341
2342#/**
2343# ogBurgSetAdminKeys num_disk num_part str_bolean
[872b044]2344#@brief ver ogBootLoaderSetAdminKeys
[deacf00]2345#@see ogBootLoaderSetAdminKeys
[872b044]2346#*/ ##
[d2c8674]2347function ogBurgSetAdminKeys  ()
2348{
[deacf00]2349    # Si se solicita, mostrar ayuda.
2350    if [ "$*" == "help" ]; then
2351        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2352               "$FUNCNAME 1 4 TRUE" \
2353               "$FUNCNAME \$(ogFindCache) FALSE"               
2354        return
2355    fi
2356    ogBootLoaderSetAdminKeys $@
2357    return $?
2358}
2359
2360
2361
2362#/**
2363# ogBootLoaderSetAdminKeys
2364#@brief   Activa/Desactica las teclas de administracion
2365#@param   int_disk_SecondStage     
2366#@param   int_part_SecondStage 
2367#@param   Boolean TRUE/FALSE   
2368#@return 
2369#@exception OG_ERR_FORMAT    Formato incorrecto.
2370#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2371#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2372#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2373#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2374#@author  Antonio J. Doblas Viso. Universidad de Malaga
2375#@date    2018-01-24
2376#*/ ##
[d2c8674]2377function  ogBootLoaderSetAdminKeys ()
2378{
[deacf00]2379
2380# Variables locales.
2381local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2382
2383# Si se solicita, mostrar ayuda.
2384if [ "$*" == "help" ]; then
2385    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2386    return   
2387fi
2388 
2389
2390# Nombre de la función que llama a esta.
2391FUNC="${FUNCNAME[@]:1}"
2392FUNC="${FUNC%%\ *}"
2393
2394
2395# Error si no se reciben 2 parametros.
2396[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2397
2398# Error si no puede montar sistema de archivos.
2399PART=$(ogMount $1 $2) || return $?
2400# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2401case "$FUNC" in
2402    ogGrubSetAdminKeys)
[da53464]2403        BOOTLOADER="grub"
[deacf00]2404        BOOTLOADERDIR="grubMBR"
2405        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2406        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2407        return $?       
2408        ;;
2409    ogBurgSetAdminKeys)
2410        BOOTLOADER="burg"
2411        BOOTLOADERDIR="burg"
2412        CFGFILE="$PART/boot/burg/burg.cfg"       
2413        ;;
2414    *)
2415        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2416        return $?
2417        ;;
2418esac
2419
2420
2421# Comprobamos que exista fichero de configuración
2422[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2423
2424
2425case "$3" in
2426        true|TRUE)
2427                [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey
2428        ;;
2429        false|FALSE)
2430                [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled
2431        ;;     
2432        *)
2433           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2434        return $?
2435    ;; 
2436esac
2437}
2438
2439
2440
2441#/**
2442# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
[872b044]2443#@brief ver ogBootLoaderSetTimeOut
[deacf00]2444#@see ogBootLoaderSetTimeOut
[872b044]2445#*/ ##
[d2c8674]2446function ogGrubSetTimeOut ()
2447{
[deacf00]2448    # Si se solicita, mostrar ayuda.
2449    if [ "$*" == "help" ]; then
2450        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2451               "$FUNCNAME 1 4 50 "\
2452               "$FUNCNAME \$(ogFindCache) 50"
2453        return
2454    fi
2455    ogBootLoaderSetTimeOut $@
2456    return $?
2457}
2458
2459#/**
2460# ogBurgSetTimeOut num_disk num_part str_bolean
[872b044]2461#@brief ver ogBootLoaderSetTimeOut
[deacf00]2462#@see ogBootLoaderSetTimeOut
[872b044]2463#*/ ##
2464function ogBurgSetTimeOut ()
2465{
[deacf00]2466    # Si se solicita, mostrar ayuda.
2467    if [ "$*" == "help" ]; then
2468        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2469               "$FUNCNAME 1 4 50" \
2470               "$FUNCNAME \$(ogFindCache) 50"               
2471        return
2472    fi
2473    ogBootLoaderSetTimeOut $@
2474    return $?
2475}
2476
2477
[da53464]2478#/**
2479# ogRefindSetTimeOut int_timeout_second
2480#@brief ver ogBootLoaderSetTimeOut
2481#@see ogBootLoaderSetTimeOut
2482#*/ ##
2483function ogRefindSetTimeOut ()
2484{
2485    local EFIDISK EFIPART
2486    # Si se solicita, mostrar ayuda.
2487    if [ "$*" == "help" ]; then
2488        ogHelp "$FUNCNAME" "$FUNCNAME int_timeout_seconds" \
2489               "$FUNCNAME 50"
2490        return
2491    fi
2492
2493    read EFIDISK EFIPART <<< $(ogGetEsp)
2494    ogBootLoaderSetTimeOut $EFIDISK $EFIPART $@
2495    return $?
2496}
[deacf00]2497
2498#/**
2499# ogBootLoaderSetTimeOut
2500#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2501#@param   int_disk_SecondStage     
2502#@param   int_part_SecondStage 
2503#@param   int_timeout_seconds   
2504#@return 
2505#@exception OG_ERR_FORMAT    Formato incorrecto.
2506#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2507#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2508#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2509#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2510#@author  Antonio J. Doblas Viso. Universidad de Malaga
2511#@date    2018-01-24
2512#*/ ##
[d2c8674]2513function  ogBootLoaderSetTimeOut ()
2514{
[deacf00]2515
2516# Variables locales.
2517local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2518
2519# Si se solicita, mostrar ayuda.
2520if [ "$*" == "help" ]; then
[da53464]2521    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut"
[deacf00]2522    return   
2523fi
2524 
2525ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2526
2527# Nombre de la función que llama a esta.
2528FUNC="${FUNCNAME[@]:1}"
2529FUNC="${FUNC%%\ *}"
2530
2531# Error si no se reciben 3 parametros.
2532[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2533
2534# Error si no puede montar sistema de archivos.
2535PART=$(ogMount $1 $2) || return $?
[da53464]2536# La función debe ser llamanda desde ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut.
[deacf00]2537case "$FUNC" in
2538    ogGrubSetTimeOut)
[da53464]2539        BOOTLOADER="grub"
2540        BOOTLOADERDIR="boot/grubMBR"
[deacf00]2541        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2542        ;;
2543    ogBurgSetTimeOut)
2544        BOOTLOADER="burg"
[da53464]2545        BOOTLOADERDIR="boot/burg"
[deacf00]2546        CFGFILE="$PART/boot/burg/burg.cfg"       
2547        ;;
[da53464]2548    ogRefindSetTimeOut)
2549        BOOTLOADER="refind"
2550        BOOTLOADERDIR="EFI/refind"
2551        CFGFILE="$PART/EFI/refind/refind.conf"
2552        ;;
[deacf00]2553    *)
[da53464]2554        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut."
[deacf00]2555        return $?
2556        ;;
2557esac
2558
2559# Comprobamos que exista fichero de configuración
2560[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2561
2562# Asignamos el timeOut.
[da53464]2563if [ "$BOOTLOADER" == "refind" ]; then
2564    sed -i s/timeout.*$/"timeout $TIMEOUT"/g $CFGFILE
2565else
2566    sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2567fi
[deacf00]2568}
2569
2570
2571#/**
2572# ogGrubSetResolution num_disk num_part int_resolution
[872b044]2573#@brief ver ogBootLoaderSetResolution
[deacf00]2574#@see ogBootLoaderSetResolution
[872b044]2575#*/ ##
[d2c8674]2576function ogGrubSetResolution ()
2577{
[deacf00]2578    # Si se solicita, mostrar ayuda.
2579    if [ "$*" == "help" ]; then
2580        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2581             "$FUNCNAME 1 4 1024x768" \
2582             "$FUNCNAME \$(ogFindCache) 1024x768" \
2583             "$FUNCNAME 1 4" 
2584        return
2585    fi
2586    ogBootLoaderSetResolution $@
2587    return $?
2588}
2589
2590#/**
2591# ogBurgSetResolution num_disk num_part str_bolean
[872b044]2592#@brief ver ogBootLoaderSetResolution
[deacf00]2593#@see ogBootLoaderSetResolution
[872b044]2594#*/ ##
[d2c8674]2595function ogBurgSetResolution ()
2596 {
[deacf00]2597    # Si se solicita, mostrar ayuda.
2598    if [ "$*" == "help" ]; then
2599        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2600               "$FUNCNAME 1 4 1024x768" \
2601               "$FUNCNAME \$(ogFindCache) 1024x768" \
2602               "$FUNCNAME 1 4"               
2603        return
2604    fi
2605    ogBootLoaderSetResolution $@
2606    return $?
2607}
2608
2609
2610
2611#/**
2612# ogBootLoaderSetResolution
2613#@brief   Define la resolucion que usuara el thema del gestor de arranque
2614#@param   int_disk_SecondStage     
2615#@param   int_part_SecondStage 
2616#@param   str_resolution (Opcional)   
2617#@return 
2618#@exception OG_ERR_FORMAT    Formato incorrecto.
2619#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2620#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2621#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2622#@author  Antonio J. Doblas Viso. Universidad de Malaga
2623#@date    2018-01-24
2624#*/ ##
[d2c8674]2625function  ogBootLoaderSetResolution ()
2626{
[deacf00]2627
2628# Variables locales.
2629local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2630
2631# Si se solicita, mostrar ayuda.
2632if [ "$*" == "help" ]; then
[da53464]2633    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution, ogBurgSetResolution or ogRefindSetResolution."
[deacf00]2634    return   
2635fi
2636
2637
2638# Nombre de la función que llama a esta.
2639FUNC="${FUNCNAME[@]:1}"
2640FUNC="${FUNC%%\ *}"
2641
2642
2643# Error si no se reciben 2 parametros.
2644[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2645
2646# Error si no puede montar sistema de archivos.
2647PART=$(ogMount $1 $2) || return $?
[da53464]2648# La función debe ser llamanda desde ogGrugSetResolution, ogBurgSetResolution or ogRefindSetResolution.
[deacf00]2649case "$FUNC" in
2650    ogGrubSetResolution)
[da53464]2651        BOOTLOADER="grub"
[deacf00]2652        BOOTLOADERDIR="grubMBR"
2653        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2654        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2655        return $?     
2656        ;;
2657    ogBurgSetResolution)
2658        BOOTLOADER="burg"
2659        BOOTLOADERDIR="burg"
2660        CFGFILE="$PART/boot/burg/burg.cfg"       
2661        ;;
2662    *)
[da53464]2663        ogRaiseError $OG_ERR_FORMAT "Use GrugSetResolution, ogBurgSetResolution or ogRefindSetResolution."
[deacf00]2664        return $?
2665        ;;
2666esac
2667
2668DEFAULTRESOLUTION=1024x768
2669
2670# Comprobamos que exista fichero de configuración
2671[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2672
2673#controlar variable a consierar vga (default template) o video (menu)
2674#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2675if [ $# -eq 2 ] ; then 
2676        if [ -n $video ]; then
2677                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2678        fi
2679        if [ -n $vga ] ; then
2680        case "$vga" in
2681                788|789|814)
2682                        NEWRESOLUTION=800x600
2683                        ;;
2684                791|792|824)
2685                        NEWRESOLUTION=1024x768
2686                        ;;
2687                355)
2688                        NEWRESOLUTION=1152x864
2689                        ;;
2690                794|795|829)
2691                        NEWRESOLUTION=1280x1024
2692                        ;;
2693        esac
2694        fi
2695fi
2696
2697if [ $# -eq 3 ] ; then
2698        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2699        ogCheckStringInReg $3 "[0-9]{3,4}[x][0-9]{3,4}\$" &&  NEWRESOLUTION="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a valid resolution: 800x600, 1024x768, 1152x864, 1280x1024, 1600x1200"
2700fi
2701
2702# Si no existe NEWRESOLUCION  asignamos la defaulT
2703[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2704
2705#Cambiamos la entrada el fichero de configuración.
2706sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2707}
[6bb748b]2708
[da53464]2709
2710
2711
2712#/**
2713# ogBootLoaderSetResolution
2714#@brief   Define la resolucion que usuara el thema del gestor de arranque
2715#@param   int_resolution1
2716#@param   int_resolution2 (Opcional)
2717#@return
2718#@exception OG_ERR_FORMAT    Formato incorrecto.
2719#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2720#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2721#*/ ##
2722function ogRefindSetResolution () {
2723local PART CFGFILE
2724# Si se solicita, mostrar ayuda.
2725if [ "$*" == "help" ]; then
2726    ogHelp "$FUNCNAME" "$FUNCNAME int_resolution1 [int_resolution2]" \
2727       "$FUNCNAME 1366 768" \
2728       "$FUNCNAME 1"
2729    return
2730fi
2731
2732    # Error si no se reciben 2 parametros.
2733[ $# -ge 1 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_resolution1 [int_resolution2]" || return $?
2734
2735# Error si no puede montar sistema de archivos.
2736PART=$(ogMount $(ogGetEsp)) || return $?
2737
2738# Comprobamos que exista fichero de configuración
2739CFGFILE=$PART/EFI/refind/refind.conf
2740[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2741
2742# Borramos resolucion anterior y configuramos la nueva
2743sed -i /^resolution/d $CFGFILE
2744
2745sed -i "1 i\resolution $1 $2" $CFGFILE
2746}
2747
[17e90bd]2748#         ogRefindInstall bool_autoconfig
[6bb748b]2749#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2750#@param   bolean_Check__auto_config   true | false[default]
2751#@return
2752#@exception OG_ERR_FORMAT    Formato incorrecto.
[17e90bd]2753#@exception OG_ERR_NOTFOUND  No se encuentra la partición ESP.
2754#@exception OG_ERR_NOTFOUND  No se encuentra shimx64.efi.signed.
2755#@exception OG_ERR_NOTFOUND  No se encuentra refind-install o refind en OGLIB
2756#@exception OG_ERR_PARTITION No se puede montar la partición ESP.
2757#@note    Refind debe estar instalado en el ogLive o compartido en OGLIB
[6bb748b]2758#@version 1.1.0 - Primeras pruebas.
2759#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2760#@date    2017-06-26
[17e90bd]2761#@version 1.1.1 - Usa refind-install. Obtiene partición con ogGetEsp. Configura Part-X-Y y ogLive.
2762#@author  Irina Gomez. Universidad de Sevilla.
2763#@date    2019-03-22
[6bb748b]2764#*/ ##
[17e90bd]2765function ogRefindInstall () {
[6bb748b]2766# Variables locales.
[fae14f68]2767local CONFIG EFIDISK EFIPART EFIDEVICE EFIMNT EFIDIR SHIM REFINDDIR
2768local CACHEDEVICE OGLIVE OGLIVEDIR CMDLINE OGICON CFGFILE DEVICES
2769local LNXCFGFILE NUMENTRY DIR
[6bb748b]2770
2771# Si se solicita, mostrar ayuda.
2772if [ "$*" == "help" ]; then
[17e90bd]2773    ogHelp "$FUNCNAME" "$FUNCNAME boolean_autoconfig " \
[da53464]2774           "$FUNCNAME TRUE"
[6bb748b]2775    return
2776fi
2777
[17e90bd]2778# Recogemos parametros
2779CONFIG=${1:-"FALSE"}
2780
2781read -e EFIDISK EFIPART  <<< $(ogGetEsp)
2782EFIDEVICE=$(ogDiskToDev $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_NOTFOUND "ESP" || return $?
2783EFIMNT=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR mount ESP" || return $?
2784EFIDIR="$EFIMNT/EFI"
2785[ -d $EFIDIR ] || mkdir $EFIDIR
2786
[418feb1]2787# Comprobamos que exista shimx64
2788SHIM=$(ogGetPath /usr/lib/shim/shimx64.efi.signed)
2789[ "$SHIM" == "" ] && return $(ogRaiseError $OG_ERR_NOTFOUND "shimx64.efi.signed")
[17e90bd]2790
[418feb1]2791# Si existe configuración anterior de refind la borro
2792[ -d "$EFIDIR/refind" ] && rm -rf $EFIDIR/refind
[17e90bd]2793
[418feb1]2794# Instalamos rEFInd.
2795refind-install --yes --alldrivers --root $EFIMNT --shim $SHIM
[17e90bd]2796
[418feb1]2797# Firmo refind con certificado de OpenGnsys
2798mv $EFIDIR/refind/grubx64.efi $EFIDIR/refind/grubx64.efi-unsigned
2799sbsign --key $OGETC/ssl/private/opengnsys.key --cert  $OGETC/ssl/certs/opengnsys.crt --output $EFIDIR/refind/grubx64.efi $EFIDIR/refind/grubx64.efi-unsigned
2800
2801# Copio los certificados
2802cp /etc/refind.d/keys/* $EFIDIR/refind/keys
2803# Copio certificado opengnsys
2804cp $OGETC/ssl/certs/opengnsys.* $EFIDIR/refind/keys
2805
2806# Ponemos la entrada en NVRAM en el segundo lugar del orden de arranque
2807NEWORDER="$(ogNvramGetOrder|awk '{gsub(",", " "); printf "%x %x %s\n", $2, $1, substr($0, index($0,$3))}')"
[b0a7050]2808ogNvramSetOrder $NEWORDER
[fae14f68]2809
[418feb1]2810# Borramos configuración linux
[67b3142]2811[ -f $EFIMNT/boot/refind_linux.conf ] && mv $EFIMNT/boot/refind_linux.conf{,.ogbackup}
[418feb1]2812
2813# Eliminamos punto de motaje (por si ejecutamos más de una vez)
2814umount $EFIMNT/boot/efi
2815
[fae14f68]2816# Para la configuración del ogLive
2817ogMountCache &>/dev/null
2818if [ $? -eq 0 ]; then
2819    # Detectamos si hay ogLive
2820    CACHEDEVICE=$(ogDiskToDev $(ogFindCache))
2821    OGLIVE=$(find $OGCAC/boot -name ogvmlinuz|head -1)
2822    # Obtenemos parametros del kernel y sustituimos root
[d7d1ec8]2823    # La línea de opciones no puede contener la cadena initrd.
2824    CMDLINE="$(cat /proc/cmdline|sed -e 's/^.*ogvmlinuz.efi //g' -e 's/^.*ogvmlinuz //g' -e 's|root=/dev/[a-z]* ||g' \
2825                     -e 's/ogupdateinitrd=[a-z]* //g')"
[fae14f68]2826    CMDLINE="root=$CACHEDEVICE ${CMDLINE#*ogvmlinuz}"
2827
2828    # Icono para la entrada de menú
2829    OGICON=$(ls $OGLIB/refind/icons/so_opengnsys.png 2>/dev/null)
2830    [ "$OGICON" == "" ] && OGICON="${EFIDIR}/refind/icons/os_unknown.png"
2831    cp "$OGICON" "$OGCAC/.VolumeIcon.png"
[6bb748b]2832fi
2833
[17e90bd]2834# Configuramos rEFInd si es necesario
[da53464]2835CFGFILE="${EFIDIR}/refind/refind.conf"
2836if [ "$CONFIG" == "TRUE" ]; then
[fae14f68]2837    echo -e "\n\n# Configuración OpenGnsys" >> $CFGFILE
2838    # Excluimos dispositivos distintos de ESP y CACHE
2839    DEVICES=$(blkid -s PARTUUID |awk -v D=$EFIDEVICE -v C=$CACHEDEVICE '$1!=D":" && $1!=C":"  {gsub(/PARTUUID=/,"");gsub(/"/,"");   aux = aux" "$2","} END {print aux}')
2840    echo "dont_scan_volumes $DEVICES" >> $CFGFILE
2841    # Excluimos en la ESP los directorios de los sistemas operativos
2842    echo "dont_scan_dirs EFI/microsoft,EFI/ubuntu,EFI/grub" >> $CFGFILE
2843    echo "use_graphics_for osx,linux,windows" >> $CFGFILE
2844    echo "showtools reboot, shutdown" >> $CFGFILE
2845
2846    # Configuramos ogLive
2847    if [ "$OGLIVE" != "" ]; then
2848        # Cambiamos nombre de kernel e initrd para que lo detecte refind
2849        OGLIVEDIR="$(dirname  $OGLIVE)"
2850        cp "$OGLIVE" "${OGLIVE}.efi"
2851        cp "$OGLIVEDIR/oginitrd.img" "$OGLIVEDIR/initrd.img"
2852
2853        # Incluimos el directorio de ogLive.
2854        echo "also_scan_dirs +,boot/$(basename $OGLIVEDIR)" >> $CFGFILE
2855        # Fichero de configuración de refind para kernel de linux.
2856        LNXCFGFILE="$OGLIVEDIR/refind_linux.conf"
2857        echo "\"OpenGnsys Live\" \"$CMDLINE\"" > $LNXCFGFILE
2858
2859        # Ponemos ogLive como la entrada por defecto
2860        NUMENTRY=$(ls -d $EFIDIR/Part-??-??|wc -l)
2861        echo "default_selection $((NUMENTRY+1))" >> $CFGFILE
2862    fi
[da53464]2863else
[17e90bd]2864    # Renombramos la configuración por defecto
[da53464]2865    mv $CFGFILE ${CFGFILE}.auto
[17e90bd]2866
2867    # Creamos nueva configuración
[fae14f68]2868    echo "# Configuración OpenGnsys" >> $CFGFILE
[17e90bd]2869    echo "timeout 20" > $CFGFILE
2870    echo "showtools reboot, shutdown" >> $CFGFILE
2871    echo -e "scanfor manual\n" >> $CFGFILE
[da53464]2872    # Configuración para sistemas restaurados con OpenGnsys
[17e90bd]2873    for DIR in $(ls -d /mnt/sda1/EFI/Part-*-* 2>/dev/null); do
2874        echo "menuentry \"${DIR##*/}\" {" >> $CFGFILE
[dd890f1]2875        echo "    loader /EFI/${DIR##*/}/Boot/ogloader.efi" >> $CFGFILE
2876        [ -f $DIR/Boot/bootmgfw.efi ] && echo "    icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
2877        [ -f $DIR/Boot/grubx64.efi ] && echo "    icon /EFI/refind/icons/os_linux.png" >> $CFGFILE
[17e90bd]2878        echo "}" >> $CFGFILE
2879    done
[8b9b6ec]2880    # Configuración ogLive si secureboot no está activado
2881    if ! dmesg|grep secureboot.*enabled &>/dev/null; then
2882        if [ "$OGLIVE" != "" ]; then
2883            echo "menuentry \"OpenGnsys Live\" {" >> $CFGFILE
2884            echo "    volume CACHE" >> $CFGFILE
2885            echo "    ostype Linux" >> $CFGFILE
2886            echo "    loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE
2887            echo "    initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE
2888            echo "    options \"$CMDLINE\"" >> $CFGFILE
2889            echo "}" >> $CFGFILE
2890
2891            # Ponemos ogLive como la entrada por defecto
2892            sed -i '1 i\default_selection "OpenGnsys Live"' $CFGFILE
2893        fi
2894    fi
[17e90bd]2895fi
2896}
[b757c67]2897
2898#/**
2899#         ogGrub4dosInstallMbr int_ndisk
2900#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
2901#@param   int_ndisk      nº de orden del disco
2902#@param   int_ndisk      nº de orden del particion
2903#@return 
2904#@exception OG_ERR_FORMAT    Formato incorrecto.
2905#@exception OG_ERR_NOTFOUND  Tipo de partición desconocido o no se puede montar.
2906#@exception  OG_ERR_NOTBIOS Equipo no firmware BIOS legacy
2907#@exception  OG_ERR_NOMSDOS Disco duro no particioniado en modo msdos
2908#@exception  OG_ERR_NOTWRITE  Particion no modificable.
2909#@version 1.1.1 - Adaptacion a OpenGnSys.
2910#@author  Alberto García Padilla / Antonio J. Doblas Viso. Universidad de Malaga
2911#@date    2009-10-17
2912#*/ ##
2913
2914function ogGrub4dosInstallMbr ()
2915{
2916# Variables locales.
2917local DISK PART  DEVICE MOUNTDISK GRUBDISK BINBDIR
2918
2919# Si se solicita, mostrar ayuda.
2920if [ "$*" == "help" ]; then
2921    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_part " \
2922           "$FUNCNAME 1 1 "
2923    return
2924fi
2925# Error si no se recibe 2 parámetros.
2926[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
2927
2928DISK="$1"
2929PART="$2"
2930
2931#Controlar existencia de disco y particion
2932DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $?
2933MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $?
2934#Controlar acceso de escritura a la particion
2935ogIsReadonly $DISK $PART &&  return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?)
2936#Controlar disco no uefi
2937ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?)
2938#Controlar particionado tipo msdos
2939ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?)
2940#Controlar la existencia del grub4dos con acceso a ntfs
2941BINDIR="${OGLIB}/grub4dos/grub4dos-0.4.6a"
2942[ -f ${BINDIR}/bootlace.com  ] || ogRaiseError $OG_ERR_NOTFOUND ": ${BINDIR}/bootlace.com" || return $?
2943
2944#instalar el bootloader de grlrd en el MBR
2945${BINDIR}/bootlace64.com $DEVICE &>/dev/null
2946#copiar grld a la particion           
2947cp ${BINDIR}/grldr $MOUNTDISK
2948#Instalar y configurar grub4dos
[4389dcc5]2949if [[ -f $MOUNTDISK/boot/grub/menu.lst ]]; then
2950        rm $MOUNTDISK/boot/grub/menu.lst
2951        rmdir /$MOUNTDISK/boot/grub
[b757c67]2952fi
[4389dcc5]2953if [[ ! -f $MOUNTDISK/boot/grub/menu.lst ]]; then
2954        mkdir -p /$MOUNTDISK/boot/grub
2955        touch /$MOUNTDISK/boot/grub/menu.lst
[b757c67]2956       
2957        GRUBDISK=$[$1-1]
2958       
[4389dcc5]2959cat << EOT >/$MOUNTDISK/boot/grub/menu.lst
[b757c67]2960##NO-TOCAR-ESTA-LINEA MBR
2961timeout 0
2962title  MBR
2963root (hd$GRUBDISK,0)
2964chainloader (hd$GRUBDISK,0)+1
2965boot
2966EOT
2967       
2968fi
[d6a0084]2969}
Note: See TracBrowser for help on using the repository browser.