source: client/engine/Boot.lib @ f028c36

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 f028c36 was 30238ab, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 UEFI Windows compatibility: necessary functions for create and restore images.

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