source: client/engine/Boot.lib @ 522f5bb

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

#802 UEFI compatibility: allows postconfigure and log in to Ubuntu.

  • Property mode set to 100755
File size: 82.0 KB
RevLine 
[b094c59]1#!/bin/bash
2#/**
3#@file    Boot.lib
4#@brief   Librería o clase Boot
5#@class   Boot
6#@brief   Funciones para arranque y post-configuración de sistemas de archivos.
[16360e4]7#@version 1.1.0
[b094c59]8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
[dc4eac6]13#         ogBoot int_ndisk int_nfilesys [str_kernel str_initrd str_krnlparams]
[b094c59]14#@brief   Inicia el proceso de arranque de un sistema de archivos.
[42669ebf]15#@param   int_ndisk      nº de orden del disco
[16360e4]16#@param   int_nfilesys   nº de orden del sistema de archivos
17#@param   str_krnlparams parámetros de arranque del kernel (opcional)
[b094c59]18#@return  (activar el sistema de archivos).
19#@exception OG_ERR_FORMAT    Formato incorrecto.
20#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
21#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
22#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
[16360e4]23#@note    En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB.
[f5432db7]24#@note    En Linux, debe arrancarse la partición del directorio \c /boot
[3915005]25#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib 
[985bef0]26#@author  Antonio J. Doblas Viso, Universidad de Malaga
[e05993a]27#@date    2008-10-27
[3915005]28#@version 0.9 - Adaptación para OpenGnSys.
[b094c59]29#@author  Ramon Gomez, ETSII Universidad de Sevilla
30#@date    2009-09-11
[40ad2e8d]31#@version 1.0.4 - Soporta modo de arranque Windows (parámetro de inicio "winboot").
32#@author  Ramon Gomez, ETSII Universidad de Sevilla
33#@date    2012-04-12
[8fc2631]34#@version 1.0.6 - Selección a partir de tipo de sistema operativo (en vez de S.F.) y arrancar Linux con /boot separado.
[2b2f533]35#@author  Ramon Gomez, ETSII Universidad de Sevilla
[8fc2631]36#@date    2015-06-05
[16360e4]37#@version 1.1.0 - Nuevo parámetro opcional con opciones de arranque del Kernel.
38#@author  Ramon Gomez, ETSII Universidad de Sevilla
39#@date    2015-07-15
[1e7eaab]40#*/ ##
[42669ebf]41function ogBoot ()
42{
[b094c59]43# Variables locales.
[40ad2e8d]44local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
[522f5bb]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
[522f5bb]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/}
94            #ogGrubUEFIConf $1 $2 $DIRGRUB || return $?
95
[6893030]96            # Borrar cargador guardado con la misma etiqueta.
[522f5bb]97            BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
[6893030]98            BOOTNO=$(efibootmgr -v | awk -v L=$BOOTLABEL '{if ($2==L) print $1}')
[522f5bb]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).
[522f5bb]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}')
[522f5bb]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.
178        reboot
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
[ab82469]735#*/ ##
736
[d2c8674]737function ogGrubInstallMbr ()
738{
[ab82469]739
740# Variables locales.
[1c69be8]741local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[522f5bb]742local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
[ab82469]743
744# Si se solicita, mostrar ayuda.
745if [ "$*" == "help" ]; then
[9c535e0]746    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
747           "$FUNCNAME 1 1 FALSE " \
748           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
[ab82469]749    return
[9c535e0]750fi 
[ab82469]751
752# Error si no se reciben 2 parámetros.
[9c535e0]753[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
[ab82469]754
755
[9c535e0]756DISK=$1; PART=$2;
757CHECKOS=${3:-"FALSE"}
758KERNELPARAM=$4
[1c69be8]759BACKUPNAME=".backup.og"
[ab82469]760
[9c535e0]761#Error si no es linux.
762#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
[a4b1e2a]763#VERSION=$(ogGetOsVersion $DISK $PART)
764#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
[ab82469]765
[59c5b66]766#La primera etapa del grub se fija en el primer disco duro
767FIRSTSTAGE=$(ogDiskToDev 1)
[ab82469]768
[9c535e0]769#localizar disco segunda etapa del grub
[522f5bb]770SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
[ab82469]771
[a4b1e2a]772# prepara el directorio principal de la segunda etapa
773[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
774
[9c535e0]775#Localizar directorio segunda etapa del grub   
776PREFIXSECONDSTAGE="/boot/grubMBR"
[ab82469]777
[522f5bb]778# Instalamos grub para EFI en ESP
779if ogIsEfiActive; then
780    read EFIDISK EFIPART <<< $(ogGetEsp)
781    # Comprobamos que exista ESP y el directorio para ubuntu
782    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
783    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
784    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
785    #Instalar el grub
786    grub-install --force --target x86_64-efi --efi-directory=${EFISECONDSTAGE} --root-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR $FIRSTSTAGE
787    # Solo para ubuntu: falta generalizar
788    mv -v $EFISECONDSTAGE/EFI/ubuntu/grubx64.efi $EFISECONDSTAGE/EFI/$EFISUBDIR
789fi
790
[9c535e0]791# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
[1c69be8]792if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]793then
794    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
795    then
[1c69be8]796        # Si no se reconfigura se utiliza el grub.cfg orginal
797        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
798                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
799        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
800        # Reactivamos el grub con el grub.cfg original.
[522f5bb]801        if ogIsEfiActive; then
802            # Configuración de grub.cfg para EFI
803            ogGrubUEFIConf $1 $2
804        else
805            grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
806        fi
[9c535e0]807        return $?
808    fi
809fi
810
811# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
[52b9a3f]812
813#llamada a updateBootCache para que aloje la primera fase del ogLive
814updateBootCache
815
[9c535e0]816#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
817echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
818echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
[ab82469]819
[9c535e0]820#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
[1c69be8]821[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
[9c535e0]822
823#Preparar configuración segunda etapa: crear ubicacion
824mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
[09803ea]825#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
826sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
827/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
[9c535e0]828#Preparar configuración segunda etapa: crear entrada del sistema operativo
829grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
830
[522f5bb]831# Instalar el grub no EFI, configurar EFI
832# Para EFI en ESP para otros en la partición de sistema.
833if ogIsEfiActive; then
834    ogGrubUEFIConf $1 $2 ${PREFIXSECONDSTAGE}
835else
836    grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
837fi
[9c535e0]838}
[ab82469]839
840
[872b044]841#/**
[9c535e0]842#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
843#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
844#@param   int_disk_SecondStage     
845#@param   int_part_SecondStage     
846#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
847#@param   str "kernel param "   
848#@return 
849#@exception OG_ERR_FORMAT    Formato incorrecto.
850#@version 1.0.2 - Primeras pruebas.
851#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
852#@date    2011-10-29
853#@version 1.0.3 - Soporte para linux de 32 y 64 bits
854#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
855#@date    2012-03-13
856#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
857#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
858#@date    2012-03-13
859#*/ ##
[ab82469]860
[d2c8674]861function ogGrubInstallPartition ()
862{
[ab82469]863
[9c535e0]864# Variables locales.
[1c69be8]865local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
[522f5bb]866local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR
[9c535e0]867
868# Si se solicita, mostrar ayuda.
869if [ "$*" == "help" ]; then
870    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
871           "$FUNCNAME 1 1 FALSE " \
872           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
873    return
874fi 
875
876# Error si no se reciben 2 parámetros.
877[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
878
879DISK=$1; PART=$2;
880CHECKOS=${3:-"FALSE"}
881KERNELPARAM=$4
[1c69be8]882BACKUPNAME=".backup.og"
[9c535e0]883
884#error si no es linux.
885VERSION=$(ogGetOsVersion $DISK $PART)
886echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
887
888#Localizar primera etapa del grub
889FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
890
891#localizar disco segunda etapa del grub
892SECONDSTAGE=$(ogMount $DISK $PART)
893
894#Localizar directorio segunda etapa del grub   
895PREFIXSECONDSTAGE="/boot/grubPARTITION"
896
[522f5bb]897# Si es EFI instalamos el grub en la ESP
898if ogIsEfiActive; then
899    read EFIDISK EFIPART <<< $(ogGetEsp)
900    # Comprobamos que exista ESP y el directorio para ubuntu
901    EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
902    EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
903    [ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] || mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR
904    #Instalar el grub
905    grub-install --force --target x86_64-efi --efi-directory ${EFISECONDSTAGE} --root-directory=${EFISECONDSTAGE}/EFI/ubuntu  $FIRSTSTAGE
906    # Solo para ubuntu: falta generalizar
907    mv -v $EFISECONDSTAGE/EFI/ubuntu/grubx64.efi $EFISECONDSTAGE/EFI/$EFISUBDIR
908fi
909
[9c535e0]910# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
[1c69be8]911if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
[9c535e0]912then
913    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
914    then
[1c69be8]915        # Si no se reconfigura se utiliza el grub.cfg orginal
916        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
917                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
918        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
919        # Reactivamos el grub con el grub.cfg original.
[522f5bb]920        if ogIsEfiActive; then
921            # Configuración de grub.cfg para EFI
922            ogGrubUEFIConf $1 $2
923        else
924            grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
925        fi
[9c535e0]926        return $?
927    fi
928fi
929
930# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
931#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
932echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
933echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
934
[1c69be8]935#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
936[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
[9c535e0]937
938#Preparar configuración segunda etapa: crear ubicacion
939mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
[09803ea]940#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
941sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
942/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
[9c535e0]943#Preparar configuración segunda etapa: crear entrada del sistema operativo
944grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
945
[522f5bb]946#Instalar el grub si no es EFI, configurar si es EFI
947if ogIsEfiActive; then
948    ogGrubUEFIConf $1 $2 ${PREFIXSECONDSTAGE}
949else
950    grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
951fi
[ab82469]952}
953
[fd0d6e5]954
[00cede9]955#/**
[c9c2f1d1]956#         ogConfigureFstab int_ndisk int_nfilesys
[870619d]957#@brief   Configura el fstab según particiones existentes
[00cede9]958#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]959#@param   int_nfilesys   nº de orden del sistema de archivos
[00cede9]960#@return  (nada)
961#@exception OG_ERR_FORMAT    Formato incorrecto.
[c9c2f1d1]962#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
963#@warning Puede haber un error si hay más de 1 partición swap.
[870619d]964#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
965#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
[c9c2f1d1]966#@date    2013-03-21
[870619d]967#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. 
968#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
969#@date    2016-11-03
[522f5bb]970#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
971#@author  Irina Gómez, ETSII Universidad de Sevilla
972#@date    2018-12-13
[00cede9]973#*/ ##
[d2c8674]974function ogConfigureFstab ()
975{
[00cede9]976# Variables locales.
[c9c2f1d1]977local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
[522f5bb]978local EFIDISK EFIPART DEVEFI OPTEFI
[00cede9]979
980# Si se solicita, mostrar ayuda.
981if [ "$*" == "help" ]; then
[c9c2f1d1]982    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
983           "$FUNCNAME 1 1"
[00cede9]984    return
985fi
986# Error si no se reciben 2 parámetros.
987[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[c9c2f1d1]988# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
989FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
990[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
991
992# Hacer copia de seguridad del fichero fstab original.
993cp -a ${FSTAB} ${FSTAB}.backup
994# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
995DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
996PARTROOT=$(ogDiskToDev $1 $2)
[200635a]997# Configuración de swap (solo 1ª partición detectada).
998PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
[00cede9]999if [ -n "$PARTSWAP" ]
1000then
[c9c2f1d1]1001    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
1002    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
[00cede9]1003    if [ -n "$DEFSWAP" ]
[c9c2f1d1]1004    then
[870619d]1005        echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
[c9c2f1d1]1006        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
[00cede9]1007    else
[870619d]1008        echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero"   # Mensaje temporal.
[c9c2f1d1]1009        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
1010        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
[00cede9]1011    fi 
1012else
[870619d]1013    echo "No hay partición SWAP -> configuramos FSTAB"  # Mensaje temporal.
1014    sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
[00cede9]1015fi
[522f5bb]1016# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
1017if [ ogIsEfiActive ]; then
1018    read EFIDISK EFIPART <<< $(ogGetEsp)
1019    DEVEFI=$(ogDiskToDev $EFIDISK $EFIPART)
[9c535e0]1020
[522f5bb]1021    # Opciones de la partición ESP: si no existe ponemos un valor por defecto
1022    OPTEFI=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
1023    OPTEFI=${OPTEFI:-vfat\tumask=0077\t0\t1}
[c9c2f1d1]1024
[522f5bb]1025    sed -i /"boot\/efi"/d  ${FSTAB}
1026    echo -e "$DEVEFI\t/boot/efi\tvfat\tumask=0077\t0\t1" >> ${FSTAB}
1027fi
1028}
[872b044]1029
[764f50e]1030#/**
[c9c2f1d1]1031#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
[764f50e]1032#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
1033#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]1034#@param   int_nfilesys   nº de orden del sistema de archivos
1035#@param   str_name       nombre asignado (opcional)
[764f50e]1036#@return  (nada)
1037#@exception OG_ERR_FORMAT    Formato incorrecto.
1038#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1039#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[c9c2f1d1]1040#@note    Si no se indica nombre, se asigna un valor por defecto.
1041#@version 1.0.5 - Primera versión para OpenGnSys.
1042#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1043#@date    2013-03-21
[764f50e]1044#*/ ##
1045function ogSetLinuxName ()
1046{
1047# Variables locales.
[c9c2f1d1]1048local MNTDIR ETC NAME
[764f50e]1049
1050# Si se solicita, mostrar ayuda.
1051if [ "$*" == "help" ]; then
[c9c2f1d1]1052    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
1053           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
[764f50e]1054    return
1055fi
[c9c2f1d1]1056# Error si no se reciben 2 o 3 parámetros.
1057case $# in
1058    2)   # Asignar nombre automático (por defecto, "pc").
1059         NAME="$(ogGetHostname)"
1060         NAME=${NAME:-"pc"} ;;
1061    3)   # Asignar nombre del 3er parámetro.
1062         NAME="$3" ;;
1063    *)   # Formato de ejecución incorrecto.
1064         ogRaiseError $OG_ERR_FORMAT
1065         return $?
1066esac
[764f50e]1067
1068# Montar el sistema de archivos.
[5962edd]1069MNTDIR=$(ogMount $1 $2) || return $?
[764f50e]1070
1071ETC=$(ogGetPath $1 $2 /etc)
1072
1073if [ -d "$ETC" ]; then
1074        #cambio de nombre en hostname
[c9c2f1d1]1075        echo "$NAME" > $ETC/hostname
[764f50e]1076        #Opcion A para cambio de nombre en hosts
1077        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
[c9c2f1d1]1078        #Opcion B componer fichero de hosts
1079        cat > $ETC/hosts <<EOF
[764f50e]1080127.0.0.1       localhost
1081127.0.1.1       $NAME
1082
1083# The following lines are desirable for IPv6 capable hosts
1084::1     ip6-localhost ip6-loopback
1085fe00::0 ip6-localnet
1086ff00::0 ip6-mcastprefix
1087ff02::1 ip6-allnodes
1088ff02::2 ip6-allrouters
1089EOF
1090fi
1091}
1092
[df814dd0]1093
[fd0d6e5]1094
[df814dd0]1095#/**
[c9c2f1d1]1096#         ogCleanLinuxDevices int_ndisk int_nfilesys
[df814dd0]1097#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
1098#@param   int_ndisk      nº de orden del disco
[c9c2f1d1]1099#@param   int_nfilesys   nº de orden del sistema de archivos
[df814dd0]1100#@return  (nada)
1101#@exception OG_ERR_FORMAT    Formato incorrecto.
1102#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1103#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
[c9c2f1d1]1104#@version 1.0.5 - Primera versión para OpenGnSys.
1105#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1106#@date    2013-03-21
[fd0d6e5]1107#@version 1.0.6b - Elimina fichero resume de hibernacion
1108#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1109#@date    2016-11-07
[df814dd0]1110#*/ ##
1111function ogCleanLinuxDevices ()
1112{
1113# Variables locales.
[c9c2f1d1]1114local MNTDIR
[df814dd0]1115
1116# Si se solicita, mostrar ayuda.
1117if [ "$*" == "help" ]; then
[c9c2f1d1]1118    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
1119           "$FUNCNAME 1 1"
[df814dd0]1120    return
1121fi
1122# Error si no se reciben 2 parámetros.
1123[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1124
1125# Montar el sistema de archivos.
[5962edd]1126MNTDIR=$(ogMount $1 $2) || return $?
[df814dd0]1127
[c9c2f1d1]1128# Eliminar fichero de configuración de udev para dispositivos fijos de red.
[fd0d6e5]1129[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
1130# Eliminar fichero resume  (estado previo de hibernación) utilizado por el initrd scripts-premount
1131[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
[df814dd0]1132}
1133
[512c692]1134#/**
[e44e88a]1135# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
[512c692]1136#@brief   Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
1137#@param 1 Numero de disco
1138#@param 2 Numero de particion
[1a2fa9d8]1139#@param 3 timeout  Segundos de espera para iniciar el sistema operativo por defecto (opcional)
1140#@param 4 offline  configura el modo offline [offline|online] (opcional)
[512c692]1141#@return  (nada)
1142#@exception OG_ERR_FORMAT    Formato incorrecto.
1143#@exception OG_ERR_NOTFOUND No existe kernel o initrd  en cache.
1144#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
1145# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
[e44e88a]1146#@version 1.0.6 - Prmera integración
1147#@author 
1148#@date    2016-11-07
1149#@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.
1150#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1151#@date    2017-06-17
1152#*/ ##
1153
[512c692]1154
[d2c8674]1155function ogGrubAddOgLive ()
1156{
[1a2fa9d8]1157    local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
[512c692]1158
1159    # Si se solicita, mostrar ayuda.
1160    if [ "$*" == "help" ]; then
[1a2fa9d8]1161        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
1162                "$FUNCNAME 1 1" \
1163                "$FUNCNAME 1 6 15 offline"
[512c692]1164        return
1165    fi
1166
1167    # Error si no se reciben 2 parámetros.
1168    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
[1a2fa9d8]1169    [[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
[512c692]1170
1171    # Error si no existe el kernel y el initrd en la cache.
1172    # Falta crear nuevo codigo de error.
[e44e88a]1173    [ -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]1174
1175    # Archivo de configuracion del grub
1176    DIRMOUNT=$(ogMount $1 $2)
1177    GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1178
1179    # Error si no existe archivo del grub
1180    [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$GRUBGFC" 1>&2; echo $?)
1181
[28ffb59]1182    # Si existe la entrada de opengnsys, se borra
1183    grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
[512c692]1184
1185    # Tipo de tabla de particiones
1186    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
1187
1188    # Localizacion de la cache
1189    read NUMDISK NUMPART <<< $(ogFindCache)
1190    let NUMDISK=$NUMDISK-1
1191    # kernel y sus opciones. Pasamos a modo usuario
[e44e88a]1192    KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
[1a2fa9d8]1193
1194    # Configuracion offline si existe parametro
1195    echo "$@" |grep offline &>/dev/null && STATUS=offline
1196    echo "$@" |grep online  &>/dev/null && STATUS=online
1197    [ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed  s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
1198
[512c692]1199    # Numero de línea de la primera entrada del grub.
1200    NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
1201    # Texto de la entrada de opengnsys
[e44e88a]1202MENUENTRY="menuentry "OpenGnsys"  --class opengnsys --class gnu --class os { \n \
[512c692]1203\tinsmod part_$PARTTABLETYPE \n \
1204\tinsmod ext2 \n \
1205\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
1206\tlinux $KERNEL \n \
[e44e88a]1207\tinitrd /boot/${oglivedir}/oginitrd.img \n \
[512c692]1208}"
1209
1210
1211    # Insertamos la entrada de opengnsys antes de la primera entrada existente.
1212    sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
1213
1214    # Ponemos que la entrada por defecto sea la primera.
1215    sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
1216
1217    # Si me dan valor para timeout lo cambio en el grub.
1218    [ $TIMEOUT ] &&  sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
1219}
1220
1221#/**
1222# ogGrubHidePartitions num_disk num_part
[872b044]1223#@brief ver ogBootLoaderHidePartitions
[8196942]1224#@see ogBootLoaderHidePartitions
[872b044]1225#*/ ##
[d2c8674]1226function ogGrubHidePartitions ()
1227{
[cade8c0]1228    # Si se solicita, mostrar ayuda.
1229    if [ "$*" == "help" ]; then
1230        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1231               "$FUNCNAME 1 6"
1232        return
1233    fi
[8196942]1234    ogBootLoaderHidePartitions $@
1235    return $?
1236}
1237
1238#/**
1239# ogBurgHidePartitions num_disk num_part
[872b044]1240#@brief ver ogBootLoaderHidePartitions
[8196942]1241#@see ogBootLoaderHidePartitions
[872b044]1242#*/ ##
[d2c8674]1243function ogBurgHidePartitions ()
1244{
[cade8c0]1245    # Si se solicita, mostrar ayuda.
1246    if [ "$*" == "help" ]; then
1247        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1248               "$FUNCNAME 1 6"
1249        return
1250    fi
[8196942]1251    ogBootLoaderHidePartitions $@
1252    return $?
1253}
1254
1255#/**
1256# ogBootLoaderHidePartitions num_disk num_part
1257#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
[512c692]1258#@param 1 Numero de disco
1259#@param 2 Numero de particion
1260#@return  (nada)
1261#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]1262#@exception No existe archivo de configuracion del grub/burg.
[e9c3156]1263#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
1264#@author  Irina Gomez, ETSII Universidad de Sevilla
1265#@date    2015-11-17
[8196942]1266#@version 1.1 Se generaliza la función para grub y burg
1267#@author  Irina Gomez, ETSII Universidad de Sevilla
1268#@date    2017-10-20
[872b044]1269#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1270#@author  Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
1271#@date    2018-07-05
[512c692]1272#*/
[872b044]1273
[d2c8674]1274function ogBootLoaderHidePartitions ()
1275{
[8196942]1276    local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN
1277
[512c692]1278    # Si se solicita, mostrar ayuda.
1279    if [ "$*" == "help" ]; then
[cade8c0]1280        ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
[512c692]1281        return
1282    fi
1283
[cade8c0]1284    # Nombre de la función que llama a esta.
1285    FUNC="${FUNCNAME[@]:1}"
1286    FUNC="${FUNC%%\ *}"
1287
[512c692]1288    # Error si no se reciben 2 parámetros.
1289    [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?)
1290
1291    # Archivo de configuracion del grub
1292    DIRMOUNT=$(ogMount $1 $2)
[8196942]1293    # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
1294    case "$FUNC" in
1295        ogGrubHidePartitions)
1296            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1297            ;;
1298        ogBurgHidePartitions)
1299            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1300            ;;
1301        *)
1302            ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
1303            return $?
1304            ;;
1305    esac
[512c692]1306
1307    # Error si no existe archivo del grub
[8196942]1308    [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" 1>&2; echo $?)
[512c692]1309
[e9c3156]1310    # Si solo hay una particion de Windows me salgo
[8df5ab7]1311    [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
[512c692]1312
1313    # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
[8196942]1314    sed -i '/parttool/d' $CFGFILE
[512c692]1315
1316    PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
[872b044]1317#   /*  (comentario de bloque para  Doxygen)
[512c692]1318    # Entradas de Windows: numero de linea y particion. De mayor a menor.
[8196942]1319    WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, "");  print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g)
[872b044]1320    #*/ (comentario para bloque Doxygen)
[e9c3156]1321    # Particiones de Windows, pueden no estar en el grub.
[8df5ab7]1322    WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d')
[512c692]1323    # Modifico todas las entradas de Windows.
1324    for ENTRY in $WINENTRY; do
1325        LINE=${ENTRY%:*}
[e9c3156]1326        PART=${ENTRY#*:}
[512c692]1327        # En cada entrada, oculto o muestro cada particion.
1328        TEXT=""
[e9c3156]1329        for PART2 in $WINPART; do
[512c692]1330                # Muestro solo la particion de la entrada actual.
[e9c3156]1331                [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+"
[512c692]1332
[26255c2]1333                TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT"
[512c692]1334        done
1335       
[8196942]1336        sed -i "${LINE}a\ $TEXT" $CFGFILE
[512c692]1337    done
1338
1339    # Activamos la particion que se inicia en todas las entradas de windows.
[8196942]1340    sed -i "/chainloader/i\\\tparttool \$\{root\} boot+"  $CFGFILE
[512c692]1341
1342}
1343
1344#/**
[be87371]1345# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
[872b044]1346#@brief ver ogBootLoaderDeleteEntry
1347#@see ogBootLoaderDeleteEntry
[8196942]1348#*/
[d2c8674]1349function ogGrubDeleteEntry ()
1350{
[cade8c0]1351    # Si se solicita, mostrar ayuda.
1352    if [ "$*" == "help" ]; then
[be87371]1353        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1354                "$FUNCNAME 1 6 2 1"
[cade8c0]1355        return
1356    fi
[8196942]1357    ogBootLoaderDeleteEntry $@
1358    return $?
1359}
1360
1361#/**
[be87371]1362# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
[872b044]1363#@brief ver ogBootLoaderDeleteEntry
[8196942]1364#@see ogBootLoaderDeleteEntry
1365#*/
[d2c8674]1366function ogBurgDeleteEntry ()
1367{
[cade8c0]1368    # Si se solicita, mostrar ayuda.
1369    if [ "$*" == "help" ]; then
[be87371]1370        ogHelp  "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
1371                "$FUNCNAME 1 6 2 1"
[cade8c0]1372        return
1373    fi
[8196942]1374    ogBootLoaderDeleteEntry $@
1375    return $?
1376}
1377
1378#/**
1379# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
[512c692]1380#@brief Borra en el grub las entradas para el inicio en una particion.
1381#@param 1 Numero de disco donde esta el grub
1382#@param 2 Numero de particion donde esta el grub
[be87371]1383#@param 3 Numero del disco del que borramos las entradas
1384#@param 4 Numero de la particion de la que borramos las entradas
[8196942]1385#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry
[512c692]1386#@return  (nada)
[8196942]1387#@exception OG_ERR_FORMAT    Use ogGrubDeleteEntry or ogBurgDeleteEntry.
[512c692]1388#@exception OG_ERR_FORMAT    Formato incorrecto.
[8196942]1389#@exception OG_ERR_NOTFOUND  No existe archivo de configuracion del grub.
1390#@version 1.1 Se generaliza la función para grub y burg
1391#@author  Irina Gomez, ETSII Universidad de Sevilla
1392#@date    2017-10-20
[872b044]1393#*/ ##
1394
[d2c8674]1395function ogBootLoaderDeleteEntry ()
1396{
[8196942]1397    local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY
[512c692]1398
[cade8c0]1399    # Si se solicita, mostrar ayuda.
1400    if [ "$*" == "help" ]; then
1401        ogHelp  "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry"
1402        return
1403    fi
1404
[be87371]1405    # Si el número de parámetros menos que 4 nos salimos
1406    [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
1407 
1408
[8196942]1409    # Nombre de la función que llama a esta.
1410    FUNC="${FUNCNAME[@]:1}"
1411    FUNC="${FUNC%%\ *}"
[512c692]1412
[8196942]1413    # Archivo de configuracion del grub
1414    DIRMOUNT=$(ogMount $1 $2)
1415    # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry.
1416    case "$FUNC" in
1417        ogGrubDeleteEntry)
1418            CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1419            ;;
1420        ogBurgDeleteEntry)
1421            CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1422            ;;
1423        *)
1424            ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry."
1425            return $?
1426            ;;
1427    esac
[512c692]1428
[8196942]1429    # Dispositivo
[be87371]1430    DEVICE=$(ogDiskToDev $3 $4)
[512c692]1431
1432    # Error si no existe archivo del grub)
[be87371]1433    [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND  "$CFGFILE" || return $?
[512c692]1434
[be87371]1435    # Numero de linea de cada entrada.
1436    MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
[512c692]1437
1438    # Entradas que hay que borrar.
[be87371]1439    DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
[8196942]1440
1441    # Si no hay entradas para borrar me salgo con aviso
[be87371]1442    [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $?
[512c692]1443
1444    # Recorremos el fichero del final hacia el principio.
[8196942]1445    ENDENTRY="$(wc -l $CFGFILE|cut  -d" " -f1)"
[512c692]1446    for ENTRY in $MENUENTRY; do
1447        # Comprobamos si hay que borrar la entrada.
1448        if  ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
1449            let ENDENTRY=$ENDENTRY-1
[8196942]1450            sed -i -e $ENTRY,${ENDENTRY}d  $CFGFILE
[512c692]1451        fi
1452
1453        # Guardamos el número de línea de la entrada, que sera el final de la siguiente.
1454        ENDENTRY=$ENTRY
1455    done
1456}
1457
[872b044]1458#/**
[74e01a7]1459#         ogBurgInstallMbr   int_disk_GRUBCFG  int_partition_GRUBCFG
1460#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1461#@brief   Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
1462#@param   int_disk_SecondStage     
1463#@param   int_part_SecondStage     
1464#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
1465#@return 
1466#@exception OG_ERR_FORMAT    Formato incorrecto.
[c0fde6d]1467#@exception OG_ERR_PARTITION  Partición no soportada
[74e01a7]1468#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
1469#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1470#@date    2017-06-23
[19c9dca]1471#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
1472#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1473#@date    2018-01-21
[deacf00]1474#@version 1.1.0 - Refactorizar fichero de configuacion
1475#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1476#@date    2018-01-24
[872b044]1477#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
1478#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
1479#@date    2018-07-05
[74e01a7]1480#*/ ##
1481
[d2c8674]1482function ogBurgInstallMbr ()
1483{
[74e01a7]1484 
1485# Variables locales.
1486local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
1487
1488# Si se solicita, mostrar ayuda.
1489if [ "$*" == "help" ]; then
1490    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
1491           "$FUNCNAME 1 1 FALSE " \
1492           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
1493    return
1494fi 
1495
1496# Error si no se reciben 2 parametros.
1497[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
1498
1499
1500DISK=$1; PART=$2;
1501CHECKOS=${3:-"FALSE"}
1502KERNELPARAM=$4
1503BACKUPNAME=".backup.og"
1504
1505#Error si no es linux.
1506ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?)
1507
1508
1509#La primera etapa del grub se fija en el primer disco duro
1510FIRSTSTAGE=$(ogDiskToDev 1)
1511
1512#localizar disco segunda etapa del grub
1513SECONDSTAGE=$(ogMount $DISK $PART)
1514
1515# prepara el directorio principal de la segunda etapa (y copia los binarios)
[872b044]1516[ -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]1517
1518#Copiamos el tema
1519mkdir -p  ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
[19c9dca]1520cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
[74e01a7]1521
1522#Localizar directorio segunda etapa del grub   
1523#PREFIXSECONDSTAGE="/boot/burg/"
1524
1525# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
1526if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]
1527then
1528    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
1529    then
[19c9dca]1530        burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]1531        return $?
1532    fi
1533fi
1534
1535# SI Reconfigurar segunda etapa (burg.cfg) == TRUE
1536
1537#llamada a updateBootCache para que aloje la primera fase del ogLive
1538updateBootCache
1539
1540#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
1541echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
1542echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
1543
1544
1545#Preparar configuración segunda etapa: crear ubicacion
1546mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
1547
1548#Preparar configuración segunda etapa: crear cabecera del fichero
1549#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1550
1551FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
1552
[872b044]1553#/* ## (comentario Dogygen)
[74e01a7]1554cat > "$FILECFG" << EOF
1555
1556set theme_name=OpenGnsys
1557set gfxmode=1024x768
[deacf00]1558
[74e01a7]1559
1560set locale_dir=(\$root)/boot/burg/locale
1561
1562set default=0
1563set timeout=25
1564set lang=es
1565
1566
1567insmod ext2
1568insmod gettext
1569
1570
[deacf00]1571
1572
[74e01a7]1573if [ -s \$prefix/burgenv ]; then
1574  load_env
1575fi
1576
[deacf00]1577
1578
[74e01a7]1579if [ \${prev_saved_entry} ]; then
1580  set saved_entry=\${prev_saved_entry}
1581  save_env saved_entry
1582  set prev_saved_entry=
1583  save_env prev_saved_entry
1584  set boot_once=true
1585fi
1586
1587function savedefault {
1588  if [ -z \${boot_once} ]; then
1589    saved_entry=\${chosen}
1590    save_env saved_entry
1591  fi
1592}
1593function select_menu {
1594  if menu_popup -t template_popup theme_menu ; then
1595    free_config template_popup template_subitem menu class screen
1596    load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1597    save_env theme_name
1598    menu_refresh
1599  fi
1600}
1601
1602function toggle_fold {
1603  if test -z $theme_fold ; then
1604    set theme_fold=1
1605  else
1606    set theme_fold=
1607  fi
1608  save_env theme_fold
1609  menu_refresh
1610}
1611function select_resolution {
1612  if menu_popup -t template_popup resolution_menu ; then
1613    menu_reload_mode
1614    save_env gfxmode
1615  fi
1616}
1617
1618
1619if test -f \${prefix}/themes/\${theme_name}/theme ; then
1620  insmod coreui
1621  menu_region.text
1622  load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'   
[deacf00]1623  load_config \${prefix}/themes/conf.d/10_hotkey   
[74e01a7]1624  load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
1625  insmod vbe
1626  insmod png
1627  insmod jpeg
1628  set gfxfont="Unifont Regular 16"
1629  menu_region.gfx
1630  vmenu resolution_menu
1631  controller.ext
1632fi
1633
1634
1635EOF
[872b044]1636#*/ ## (comentario Dogygen)
[74e01a7]1637
1638#Preparar configuración segunda etapa: crear entrada del sistema operativo
1639grubSyntax "$KERNELPARAM" >> "$FILECFG"
1640
1641
1642#Instalar el burg
[19c9dca]1643burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
[74e01a7]1644}
1645
[0d2e65b]1646#/**
[be87371]1647# ogGrubDefaultEntry int_disk_GRUGCFG  int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
[872b044]1648#@brief ver ogBootLoaderDefaultEntry
[be87371]1649#@see ogBootLoaderDefaultEntry
[872b044]1650#*/ ##
[d2c8674]1651function ogGrubDefaultEntry ()
1652{
[be87371]1653    # Si se solicita, mostrar ayuda.
1654    if [ "$*" == "help" ]; then
1655        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1656               "$FUNCNAME 1 6 1 1"
1657        return
1658    fi
1659    ogBootLoaderDefaultEntry $@
1660    return $?
1661}
1662
1663#/**
1664# ogBurgDefaultEntry int_disk_BURGCFG  int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
[872b044]1665#@brief ver ogBootLoaderDefaultEntry
[be87371]1666#@see ogBootLoaderDefaultEntry
[872b044]1667#*/ ##
[d2c8674]1668function ogBurgDefaultEntry ()
1669{
[be87371]1670    # Si se solicita, mostrar ayuda.
1671    if [ "$*" == "help" ]; then
1672        ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
1673               "$FUNCNAME 1 6 1 1"
1674        return
1675    fi
1676    ogBootLoaderDefaultEntry $@
1677    return $?
1678}
1679
1680#/**
1681# ogBootLoaderDefaultEntry   int_disk_CFG  int_partition_CFG int_disk_default_entry int_npartition_default_entry
[0d2e65b]1682#@brief   Configura la entrada por defecto de Burg
1683#@param   int_disk_SecondStage     
1684#@param   int_part_SecondStage     
[be87371]1685#@param   int_disk_default_entry
1686#@param   int_part_default_entry
[0d2e65b]1687#@return 
1688#@exception OG_ERR_FORMAT    Formato incorrecto.
1689#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1690#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
1691#@exception OG_ERR_NOTFOUND   Fichero de configuración no encontrado: burg.cfg.
[be87371]1692#@version 1.1.0 - Define la entrada por defecto del Burg
[0d2e65b]1693#@author  Irina Gomez, ETSII Universidad de Sevilla
1694#@date    2017-08-09
[be87371]1695#@version 1.1 Se generaliza la función para grub y burg
1696#@author  Irina Gomez, ETSII Universidad de Sevilla
1697#@date    2018-01-04
[0d2e65b]1698#*/ ##
[d2c8674]1699function ogBootLoaderDefaultEntry ()
1700{
[0d2e65b]1701
1702# Variables locales.
[be87371]1703local PART CFGFILE DEFAULTENTRY MSG
[0d2e65b]1704
1705# Si se solicita, mostrar ayuda.
1706if [ "$*" == "help" ]; then
[be87371]1707    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry"
[0d2e65b]1708    return
1709fi 
1710
[be87371]1711# Nombre de la función que llama a esta.
1712FUNC="${FUNCNAME[@]:1}"
1713FUNC="${FUNC%%\ *}"
1714
[0d2e65b]1715# Error si no se reciben 3 parametros.
[be87371]1716[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
[0d2e65b]1717
1718# Error si no puede montar sistema de archivos.
[be87371]1719DIRMOUNT=$(ogMount $1 $2) || return $?
1720
1721# Comprobamos que exista fichero de configuración
1722# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry.
1723case "$FUNC" in
1724    ogGrubDefaultEntry)
1725        CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
1726        ;;
1727    ogBurgDefaultEntry)
1728        CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
1729        ;;
1730    *)
1731        ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry."
1732        return $?
1733        ;;
1734esac
1735
1736# Error si no existe archivo de configuración
1737[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1738
1739# Dispositivo
1740DEVICE=$(ogDiskToDev $3 $4)
[0d2e65b]1741
[be87371]1742# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
1743DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1)
[0d2e65b]1744
[be87371]1745# Si no hay entradas para borrar me salgo con aviso
1746[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $?
[0d2e65b]1747
[be87371]1748# Número de la de linea por defecto en el menú de usuario
1749MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
1750# Las líneas empiezan a contar desde cero
1751let MENUENTRY=$MENUENTRY-1
1752sed --regexp-extended -i  s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE
1753MSG="MSG_HELP_$FUNC"
1754echo "${!MSG%%\.}: $@"
[0d2e65b]1755}
1756
1757#/**
[be87371]1758# ogGrubOgliveDefaultEntry num_disk num_part
[872b044]1759#@brief ver ogBootLoaderOgliveDefaultEntry
[be87371]1760#@see ogBootLoaderOgliveDefaultEntry
[872b044]1761#*/ ##
[d2c8674]1762function ogGrubOgliveDefaultEntry ()
1763{
[be87371]1764    # Si se solicita, mostrar ayuda.
1765    if [ "$*" == "help" ]; then
1766        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1767               "$FUNCNAME 1 6"
1768        return
1769    fi
1770    ogBootLoaderOgliveDefaultEntry $@
1771    return $?
1772}
1773
1774#/**
1775# ogBurgOgliveDefaultEntry num_disk num_part
[872b044]1776#@brief ver ogBootLoaderOgliveDefaultEntry
[be87371]1777#@see ogBootLoaderOgliveDefaultEntry
[872b044]1778#*/ ##
[d2c8674]1779function ogBurgOgliveDefaultEntry ()
1780{
[be87371]1781    # Si se solicita, mostrar ayuda.
1782    if [ "$*" == "help" ]; then
1783        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
1784               "$FUNCNAME 1 6"
1785        return
1786    fi
1787    ogBootLoaderOgliveDefaultEntry $@
1788    return $?
1789}
1790
1791#/**
1792# ogBootLoaderOgliveDefaultEntry
[0d2e65b]1793#@brief   Configura la entrada de ogLive como la entrada por defecto de Burg.
1794#@param   int_disk_SecondStage     
1795#@param   int_part_SecondStage     
1796#@return 
1797#@exception OG_ERR_FORMAT    Formato incorrecto.
1798#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1799#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: burg.cfg.
1800#@exception OG_ERR_NOTFOUND  Entrada de OgLive no encontrada en burg.cfg.
1801#@version 1.1.0 - Primeras pruebas con Burg
1802#@author  Irina Gomez, ETSII Universidad de Sevilla
1803#@date    2017-08-09
[be87371]1804#@version 1.1 Se generaliza la función para grub y burg
1805#@author  Irina Gomez, ETSII Universidad de Sevilla
1806#@date    2018-01-04
[0d2e65b]1807#*/ ##
[d2c8674]1808function  ogBootLoaderOgliveDefaultEntry ()
1809{
[0d2e65b]1810
1811# Variables locales.
[be87371]1812local FUNC PART CFGFILE NUMENTRY MSG
[0d2e65b]1813
1814# Si se solicita, mostrar ayuda.
1815if [ "$*" == "help" ]; then
[be87371]1816    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \
[0d2e65b]1817    return
1818fi 
1819
[be87371]1820# Nombre de la función que llama a esta.
1821FUNC="${FUNCNAME[@]:1}"
1822FUNC="${FUNC%%\ *}"
1823
[0d2e65b]1824# Error si no se reciben 2 parametros.
1825[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage" || return $?
1826
1827# Error si no puede montar sistema de archivos.
1828PART=$(ogMount $1 $2) || return $?
[be87371]1829# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry.
1830case "$FUNC" in
1831    ogGrubOgliveDefaultEntry)
1832        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
1833        ;;
1834    ogBurgOgliveDefaultEntry)
1835        CFGFILE="$PART/boot/burg/burg.cfg"
1836        ;;
1837    *)
1838        ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry."
1839        return $?
1840        ;;
1841esac
[0d2e65b]1842
[be87371]1843# Comprobamos que exista fichero de configuración
1844[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
[0d2e65b]1845
1846# Detectamos cual es la entrada de ogLive
[be87371]1847NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
[0d2e65b]1848
1849# Si no existe entrada de ogLive nos salimos
[be87371]1850[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
[0d2e65b]1851
1852let NUMENTRY=$NUMENTRY-1
[f2e6a2e]1853sed --regexp-extended -i  s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
[0d2e65b]1854
[be87371]1855MSG="MSG_HELP_$FUNC"
1856echo "${!MSG%%\.}: $@"
[0d2e65b]1857}
[74e01a7]1858
[deacf00]1859
1860#/**
1861# ogGrubSetTheme num_disk num_part str_theme
[872b044]1862#@brief ver ogBootLoaderSetTheme
[deacf00]1863#@see ogBootLoaderSetTheme
[872b044]1864#*/ ##
[d2c8674]1865function ogGrubSetTheme ()
1866{
[deacf00]1867    # Si se solicita, mostrar ayuda.
1868    if [ "$*" == "help" ]; then
1869        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1870               "$FUNCNAME 1 4 ThemeBasic"\
1871               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1872        return
1873    fi
1874    ogBootLoaderSetTheme $@
1875    return $?
1876}
1877
1878#/**
1879# ogBurgSetTheme num_disk num_part str_theme
[872b044]1880#@brief ver ogBootLoaderSetTheme
[deacf00]1881#@see ogBootLoaderSetTheme
[872b044]1882#*/ ##
[d2c8674]1883function ogBurgSetTheme  ()
1884{
[deacf00]1885    # Si se solicita, mostrar ayuda.
1886    if [ "$*" == "help" ]; then
1887        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
1888               "$FUNCNAME 1 4 ThemeBasic" \
1889               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1890        echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
1891               
1892        return
1893    fi
1894    ogBootLoaderSetTheme $@
1895    return $?
1896}
1897
1898
1899
1900#/**
1901# ogBootLoaderSetTheme
1902#@brief   asigna un tema al BURG
1903#@param   int_disk_SecondStage     
1904#@param   int_part_SecondStage 
1905#@param   str_theme_name   
1906#@return 
1907#@exception OG_ERR_FORMAT    Formato incorrecto.
1908#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
1909#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
1910#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
1911#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
1912#@author  Antonio J. Doblas Viso. Universidad de Malaga
1913#@date    2018-01-24
1914#*/ ##
[d2c8674]1915function  ogBootLoaderSetTheme ()
1916{
[deacf00]1917
1918# Variables locales.
1919local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG
1920
1921# Si se solicita, mostrar ayuda.
1922if [ "$*" == "help" ]; then
1923    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme"
1924    return   
1925fi
1926 
1927
1928NEWTHEME="$3"
1929
1930# Nombre de la función que llama a esta.
1931FUNC="${FUNCNAME[@]:1}"
1932FUNC="${FUNC%%\ *}"
1933
1934
1935
1936# Error si no se reciben 2 parametros.
1937[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
1938
1939# Error si no puede montar sistema de archivos.
1940PART=$(ogMount $1 $2) || return $?
1941# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme.
1942case "$FUNC" in
1943    ogGrubSetTheme)
1944        BOOTLOADER="grug"
1945        BOOTLOADERDIR="grubMBR"
1946        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
1947        ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
1948        return $?               
1949        ;;
1950    ogBurgSetTheme)
1951        BOOTLOADER="burg"
1952        BOOTLOADERDIR="burg"
1953        CFGFILE="$PART/boot/burg/burg.cfg"       
1954        ;;
1955    *)
1956        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme or ogBurgSetTheme."
1957        return $?
1958        ;;
1959esac
1960
1961# Comprobamos que exista fichero de configuración
1962[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
1963
1964# Detectamos cual es el tema asignado
1965THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
1966
1967# Si no existe entrada de theme_name  nos salimos
1968[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
1969
1970#Actualizamos el tema del servidor a la particion
1971if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
1972        cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/boot/$BOOTLOADERDIR/themes/   
1973fi
1974
1975#Verificamos que el tema esta en la particion
1976if ! [ -d $PART/boot/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
1977                ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/boot/$BOOTLOADERDIR/themes/" || return $?
1978fi
1979
1980#Cambiamos la entrada el fichero de configuración.
1981sed --regexp-extended -i  s/"$THEME"/"$NEWTHEME"/g $CFGFILE
1982
1983
1984}
1985
1986#/**
1987# ogGrubSetAdminKeys num_disk num_part str_theme
[872b044]1988#@brief ver ogBootLoaderSetTheme
[deacf00]1989#@see ogBootLoaderSetTheme
[872b044]1990#*/ ##
[d2c8674]1991function ogGrubSetAdminKeys ()
1992{
[deacf00]1993    # Si se solicita, mostrar ayuda.
1994    if [ "$*" == "help" ]; then
1995        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
1996               "$FUNCNAME 1 4 FALSE "\
1997               "$FUNCNAME \$(ogFindCache) ThemeBasic"
1998        return
1999    fi
2000    ogBootLoaderSetAdminKeys $@
2001    return $?
2002}
2003
2004#/**
2005# ogBurgSetAdminKeys num_disk num_part str_bolean
[872b044]2006#@brief ver ogBootLoaderSetAdminKeys
[deacf00]2007#@see ogBootLoaderSetAdminKeys
[872b044]2008#*/ ##
[d2c8674]2009function ogBurgSetAdminKeys  ()
2010{
[deacf00]2011    # Si se solicita, mostrar ayuda.
2012    if [ "$*" == "help" ]; then
2013        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
2014               "$FUNCNAME 1 4 TRUE" \
2015               "$FUNCNAME \$(ogFindCache) FALSE"               
2016        return
2017    fi
2018    ogBootLoaderSetAdminKeys $@
2019    return $?
2020}
2021
2022
2023
2024#/**
2025# ogBootLoaderSetAdminKeys
2026#@brief   Activa/Desactica las teclas de administracion
2027#@param   int_disk_SecondStage     
2028#@param   int_part_SecondStage 
2029#@param   Boolean TRUE/FALSE   
2030#@return 
2031#@exception OG_ERR_FORMAT    Formato incorrecto.
2032#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2033#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2034#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2035#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2036#@author  Antonio J. Doblas Viso. Universidad de Malaga
2037#@date    2018-01-24
2038#*/ ##
[d2c8674]2039function  ogBootLoaderSetAdminKeys ()
2040{
[deacf00]2041
2042# Variables locales.
2043local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2044
2045# Si se solicita, mostrar ayuda.
2046if [ "$*" == "help" ]; then
2047    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
2048    return   
2049fi
2050 
2051
2052# Nombre de la función que llama a esta.
2053FUNC="${FUNCNAME[@]:1}"
2054FUNC="${FUNC%%\ *}"
2055
2056
2057# Error si no se reciben 2 parametros.
2058[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
2059
2060# Error si no puede montar sistema de archivos.
2061PART=$(ogMount $1 $2) || return $?
2062# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
2063case "$FUNC" in
2064    ogGrubSetAdminKeys)
2065        BOOTLOADER="grug"
2066        BOOTLOADERDIR="grubMBR"
2067        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2068        ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
2069        return $?       
2070        ;;
2071    ogBurgSetAdminKeys)
2072        BOOTLOADER="burg"
2073        BOOTLOADERDIR="burg"
2074        CFGFILE="$PART/boot/burg/burg.cfg"       
2075        ;;
2076    *)
2077        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
2078        return $?
2079        ;;
2080esac
2081
2082
2083# Comprobamos que exista fichero de configuración
2084[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2085
2086
2087case "$3" in
2088        true|TRUE)
2089                [ -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
2090        ;;
2091        false|FALSE)
2092                [ -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
2093        ;;     
2094        *)
2095           ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
2096        return $?
2097    ;; 
2098esac
2099}
2100
2101
2102
2103#/**
2104# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
[872b044]2105#@brief ver ogBootLoaderSetTimeOut
[deacf00]2106#@see ogBootLoaderSetTimeOut
[872b044]2107#*/ ##
[d2c8674]2108function ogGrubSetTimeOut ()
2109{
[deacf00]2110    # Si se solicita, mostrar ayuda.
2111    if [ "$*" == "help" ]; then
2112        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
2113               "$FUNCNAME 1 4 50 "\
2114               "$FUNCNAME \$(ogFindCache) 50"
2115        return
2116    fi
2117    ogBootLoaderSetTimeOut $@
2118    return $?
2119}
2120
2121#/**
2122# ogBurgSetTimeOut num_disk num_part str_bolean
[872b044]2123#@brief ver ogBootLoaderSetTimeOut
[deacf00]2124#@see ogBootLoaderSetTimeOut
[872b044]2125#*/ ##
2126function ogBurgSetTimeOut ()
2127{
[deacf00]2128    # Si se solicita, mostrar ayuda.
2129    if [ "$*" == "help" ]; then
2130        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
2131               "$FUNCNAME 1 4 50" \
2132               "$FUNCNAME \$(ogFindCache) 50"               
2133        return
2134    fi
2135    ogBootLoaderSetTimeOut $@
2136    return $?
2137}
2138
2139
2140
2141#/**
2142# ogBootLoaderSetTimeOut
2143#@brief   Define el tiempo (segundos) que se muestran las opciones de inicio
2144#@param   int_disk_SecondStage     
2145#@param   int_part_SecondStage 
2146#@param   int_timeout_seconds   
2147#@return 
2148#@exception OG_ERR_FORMAT    Formato incorrecto.
2149#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2150#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2151#@exception OG_ERR_NOTFOUND  Entrada deltema no encontrada en burg.cfg.
2152#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
2153#@author  Antonio J. Doblas Viso. Universidad de Malaga
2154#@date    2018-01-24
2155#*/ ##
[d2c8674]2156function  ogBootLoaderSetTimeOut ()
2157{
[deacf00]2158
2159# Variables locales.
2160local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2161
2162# Si se solicita, mostrar ayuda.
2163if [ "$*" == "help" ]; then
2164    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut"
2165    return   
2166fi
2167 
2168ogCheckStringInReg $3 "^[0-9]{1,10}$" &&  TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
2169
2170# Nombre de la función que llama a esta.
2171FUNC="${FUNCNAME[@]:1}"
2172FUNC="${FUNC%%\ *}"
2173
2174# Error si no se reciben 3 parametros.
2175[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
2176
2177# Error si no puede montar sistema de archivos.
2178PART=$(ogMount $1 $2) || return $?
2179# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut.
2180case "$FUNC" in
2181    ogGrubSetTimeOut)
2182        BOOTLOADER="grug"
2183        BOOTLOADERDIR="grubMBR"
2184        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"     
2185        ;;
2186    ogBurgSetTimeOut)
2187        BOOTLOADER="burg"
2188        BOOTLOADERDIR="burg"
2189        CFGFILE="$PART/boot/burg/burg.cfg"       
2190        ;;
2191    *)
2192        ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut"
2193        return $?
2194        ;;
2195esac
2196
2197# Comprobamos que exista fichero de configuración
2198[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2199
2200# Asignamos el timeOut.
2201sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
2202}
2203
2204
2205#/**
2206# ogGrubSetResolution num_disk num_part int_resolution
[872b044]2207#@brief ver ogBootLoaderSetResolution
[deacf00]2208#@see ogBootLoaderSetResolution
[872b044]2209#*/ ##
[d2c8674]2210function ogGrubSetResolution ()
2211{
[deacf00]2212    # Si se solicita, mostrar ayuda.
2213    if [ "$*" == "help" ]; then
2214        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2215             "$FUNCNAME 1 4 1024x768" \
2216             "$FUNCNAME \$(ogFindCache) 1024x768" \
2217             "$FUNCNAME 1 4" 
2218        return
2219    fi
2220    ogBootLoaderSetResolution $@
2221    return $?
2222}
2223
2224#/**
2225# ogBurgSetResolution num_disk num_part str_bolean
[872b044]2226#@brief ver ogBootLoaderSetResolution
[deacf00]2227#@see ogBootLoaderSetResolution
[872b044]2228#*/ ##
[d2c8674]2229function ogBurgSetResolution ()
2230 {
[deacf00]2231    # Si se solicita, mostrar ayuda.
2232    if [ "$*" == "help" ]; then
2233        ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
2234               "$FUNCNAME 1 4 1024x768" \
2235               "$FUNCNAME \$(ogFindCache) 1024x768" \
2236               "$FUNCNAME 1 4"               
2237        return
2238    fi
2239    ogBootLoaderSetResolution $@
2240    return $?
2241}
2242
2243
2244
2245#/**
2246# ogBootLoaderSetResolution
2247#@brief   Define la resolucion que usuara el thema del gestor de arranque
2248#@param   int_disk_SecondStage     
2249#@param   int_part_SecondStage 
2250#@param   str_resolution (Opcional)   
2251#@return 
2252#@exception OG_ERR_FORMAT    Formato incorrecto.
2253#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
2254#@exception OG_ERR_NOTFOUND  Fichero de configuración no encontrado: grub.cfg burg.cfg.
2255#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
2256#@author  Antonio J. Doblas Viso. Universidad de Malaga
2257#@date    2018-01-24
2258#*/ ##
[d2c8674]2259function  ogBootLoaderSetResolution ()
2260{
[deacf00]2261
2262# Variables locales.
2263local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
2264
2265# Si se solicita, mostrar ayuda.
2266if [ "$*" == "help" ]; then
2267    ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution"
2268    return   
2269fi
2270
2271
2272# Nombre de la función que llama a esta.
2273FUNC="${FUNCNAME[@]:1}"
2274FUNC="${FUNC%%\ *}"
2275
2276
2277# Error si no se reciben 2 parametros.
2278[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
2279
2280# Error si no puede montar sistema de archivos.
2281PART=$(ogMount $1 $2) || return $?
2282# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution.
2283case "$FUNC" in
2284    ogGrubSetResolution)
2285        BOOTLOADER="grug"
2286        BOOTLOADERDIR="grubMBR"
2287        CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" 
2288        ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
2289        return $?     
2290        ;;
2291    ogBurgSetResolution)
2292        BOOTLOADER="burg"
2293        BOOTLOADERDIR="burg"
2294        CFGFILE="$PART/boot/burg/burg.cfg"       
2295        ;;
2296    *)
2297        ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution"
2298        return $?
2299        ;;
2300esac
2301
2302DEFAULTRESOLUTION=1024x768
2303
2304# Comprobamos que exista fichero de configuración
2305[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
2306
2307#controlar variable a consierar vga (default template) o video (menu)
2308#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
2309if [ $# -eq 2 ] ; then 
2310        if [ -n $video ]; then
2311                NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
2312        fi
2313        if [ -n $vga ] ; then
2314        case "$vga" in
2315                788|789|814)
2316                        NEWRESOLUTION=800x600
2317                        ;;
2318                791|792|824)
2319                        NEWRESOLUTION=1024x768
2320                        ;;
2321                355)
2322                        NEWRESOLUTION=1152x864
2323                        ;;
2324                794|795|829)
2325                        NEWRESOLUTION=1280x1024
2326                        ;;
2327        esac
2328        fi
2329fi
2330
2331if [ $# -eq 3 ] ; then
2332        #comprobamos que el parametro 3 cumple formato NNNNxNNNN
2333        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"
2334fi
2335
2336# Si no existe NEWRESOLUCION  asignamos la defaulT
2337[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
2338
2339#Cambiamos la entrada el fichero de configuración.
2340sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
2341}
[6bb748b]2342
[872b044]2343#/**
[6bb748b]2344#         ogRefindInstall  int_ndisk bool_autoconfig
2345#@brief   Instala y actualiza el gestor rEFInd en la particion EFI
2346#@param   int_ndisk
2347#@param   bolean_Check__auto_config   true | false[default]
2348#@return
2349#@exception OG_ERR_FORMAT    Formato incorrecto.
2350#@version 1.1.0 - Primeras pruebas.
2351#@author  Juan Carlos Garcia.   Universidad de ZAragoza.
2352#@date    2017-06-26
2353#*/ ##
[d2c8674]2354function ogRefindInstall ()
2355{
[6bb748b]2356
2357# Variables locales.
2358local DISK EFIDIR CONFIG EFIPARTITIONID
2359
2360
2361# Si se solicita, mostrar ayuda.
2362if [ "$*" == "help" ]; then
2363    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk boolean_autoconfig " \
2364           "$FUNCNAME 1 TRUE"
2365    return
2366fi
2367
2368# Error si no se recibe 1 parámetro.
2369[ $# -ge 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
2370
2371
2372DISK=$1
2373EFIDIR=/mnt/$(ogDiskToDev $1 1 | cut -c 6-8)$1/EFI
2374CONFIG=${2:-"FALSE"}
2375EFIPARTITIONID=$(ogGetPartitionId $1 1)
2376if [ "$EFIPARTITIONID" == "EF00" ] || [ "$EFIPARTITIONID" == "ef00" ]; then
2377    cp -pr /opt/opengnsys/lib/refind ${EFIDIR}
2378    case "$CONFIG" in
2379        FALSE)
2380        if [ -a ${EFIDIR}/ubuntu ]; then
2381            echo "menuentry \"Ubuntu\" {" >> ${EFIDIR}/refind/refind.conf
2382            echo "loader /EFI/ubuntu/grubx64.efi" >> ${EFIDIR}/refind/refind.conf
2383            echo "icon /EFI/refind/icons/os_linux.png" >> ${EFIDIR}/refind/refind.conf
2384            echo "}" >> ${EFIDIR}/refind/refind.conf
2385        fi
2386        if [ -a ${EFIDIR}/Microsoft ]; then
2387            echo "menuentry \"Windows\" {" >> ${EFIDIR}/refind/refind.conf
2388            echo "loader /EFI/Microsoft/Boot/bootmgfw.efi" >> ${EFIDIR}/refind/refind.conf
2389            echo "}" >> ${EFIDIR}/refind/refind.conf
2390        fi
2391        ;;
2392        TRUE)
2393        cp  ${EFIDIR}/refind/refind.conf.auto ${EFIDIR}/refind/refind.conf
2394        ;;
2395    esac
2396else
2397$(ogRaiseError $OG_ERR_FORMAT; echo $?)
2398fi
2399}
2400
Note: See TracBrowser for help on using the repository browser.