source: client/engine/Boot.lib @ 5b809ba

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 5b809ba was 5b809ba, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #890 ogGrubInstall includes option to secure boot.

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