source: client/engine/Boot.lib @ 9c9de82

Last change on this file since 9c9de82 was 2150f01, checked in by Irina Gómez <irinagomez@…>, 3 years ago

#1069 ogBootMbrGeneric creates the necessary hard drive signature for Windows (UEFI).

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