ogboot/client/engine/Boot.lib

2974 lines
104 KiB
Bash
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

#!/bin/bash
#/**
#@file Boot.lib
#@brief Librería o clase Boot
#@class Boot
#@brief Funciones para arranque y post-configuración de sistemas de archivos.
#@version 1.1.0
#@warning License: GNU GPLv3+
#*/
#/**
# ogBoot int_ndisk int_nfilesys [str_kernel str_initrd str_krnlparams]
#@brief Inicia el proceso de arranque de un sistema de archivos.
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@param str_krnlparams parámetros de arranque del kernel (opcional)
#@return (activar el sistema de archivos).
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@exception OG_ERR_NOTOS La partición no tiene instalado un sistema operativo.
#@note En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB.
#@note En Linux, debe arrancarse la partición del directorio \c /boot
#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib
#@author Antonio J. Doblas Viso, Universidad de Malaga
#@date 2008-10-27
#@version 0.9 - Adaptación para OpenGnSys.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2009-09-11
#@version 1.0.4 - Soporta modo de arranque Windows (parámetro de inicio "winboot").
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2012-04-12
#@version 1.0.6 - Selección a partir de tipo de sistema operativo (en vez de S.F.) y arrancar Linux con /boot separado.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2015-06-05
#@version 1.1.0 - Nuevo parámetro opcional con opciones de arranque del Kernel.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2015-07-15
#@version 1.1.1 - UEFI: Permite iniciar linux recien instalados (ticket #802 #890)
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-03-13
#*/ ##
function ogBoot ()
{
# Variables locales.
local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
local EFIDISK EFIPART EFIDIR BOOTLABEL BOOTLOADER BOOTNO DIRGRUB b
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_kernel str_initrd str_kernelparams]" \
"$FUNCNAME 1 1" "$FUNCNAME 1 2 \"/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro\""
return
fi
# Error si no se reciben 2 o 3 parámetros.
[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Detectar tipo de sistema de archivos y montarlo.
PART=$(ogDiskToDev $1 $2) || return $?
TYPE=$(ogGetOsType $1 $2) || return $?
# Error si no puede montar sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
case "$TYPE" in
Linux|Android)
# Si no se indican, obtiene los parámetros de arranque para Linux.
PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}"
# Si no existe y el UEFI buscar en particion ESP
[ -z "$PARAMS" ] && ogIsEfiActive && PARAMS="$(ogLinuxBootParameters $(ogGetEsp))"
# Si no existe, buscar sistema de archivo /boot en /etc/fstab.
if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then
# Localizar S.F. /boot en /etc/fstab del S.F. actual.
PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab))
# Montar S.F. de /boot.
MNTDIR=$(ogMount $PART) || return $?
# Buscar los datos de arranque.
PARAMS=$(ogLinuxBootParameters $PART) || exit $?
fi
read -e KERNEL INITRD APPEND <<<"$PARAMS"
# Si no hay kernel, no hay sistema operativo.
[ -n "$KERNEL" -a -e "$MNTDIR/$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
# Arrancar de partición distinta a la original.
[ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
# Comprobar tipo de sistema.
if ogIsEfiActive; then
# Comprobar si el Kernel está firmado.
if ! file -k "$MNTDIR/$KERNEL" | grep -q "EFI app"; then
ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)"
return $?
fi
BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
BOOTLOADER="shimx64.efi"
# Obtener parcición EFI.
read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
# TODO: Comprobamos que existe la BOOTLABEL, si no buscamos por sistema operativo
if [ "$(ogGetPath $EFIDISK $EFIPART EFI/$BOOTLABEL)" == "" ]; then
OSVERSION="$(ogGetOsVersion $1 $2)"
case $OSVERSION in
*SUSE*)
BOOTLABEL="opensuse"
;;
*Fedora*)
BOOTLABEL="fedora"
;;
*Ubuntu*)
BOOTLABEL="ubuntu"
;;
*)
ogRaiseError $OG_ERR_NOTFOUND "$EFIDISK $EFIPART Boot loader"; return $?
;;
esac
fi
# Crear orden de arranque (con unos valores por defecto).
ogNvramAddEntry $BOOTLABEL "/EFI/$BOOTLABEL/Boot/$BOOTLOADER"
# Marcar próximo arranque y reiniciar.
ogNvramSetNext "$BOOTLABEL"
reboot
else
# Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB.
kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
kexec -e &
fi
;;
Windows)
# Comprobar tipo de sistema.
if ogIsEfiActive; then
BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
# Obtener parcición EFI.
read -e EFIDISK EFIPART <<<"$(ogGetEsp)"
[ -n "$EFIPART" ] || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
EFIDIR=$(ogMount $EFIDISK $EFIPART) || exit $?
# Comprobar cargador (si no existe buscar por defecto en ESP).
LOADER=$(ogGetPath $EFIDIR/EFI/$BOOTLABEL/Boot/bootmgfw.efi)
[ -z "$LOADER" ] && BOOTLABEL=Microsoft && LOADER=$(ogGetPath $EFIDIR/EFI/Microsoft/Boot/bootmgfw.efi)
[ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE, EFI)" || return $?
# Crear orden de arranque (con unos valores por defecto).
ogNvramAddEntry $BOOTLABEL "/EFI${LOADER#*EFI}"
# Marcar próximo arranque y reiniciar.
ogNvramSetNext "$BOOTLABEL"
reboot
else
# Arranque BIOS: comprueba si hay un cargador de Windows.
for f in io.sys ntldr bootmgr; do
FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
[ -n "$FILE" ] && LOADER="$f"
done
[ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($TYPE)" || return $?
if [ "$winboot" == "kexec" ]; then
# Modo de arranque en caliente (con kexec).
cp $OGLIB/grub4dos/* $MNTDIR # */ (Comentario Doxygen)
kexec -l $MNTDIR/grub.exe --append=--config-file="root (hd$[$1-1],$[$2-1]); chainloader (hd$[$1-1],$[$2-1])/$LOADER; tpm --init"
kexec -e &
else
# Modo de arranque por reinicio (con reboot).
dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3
dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3
dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3
if [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then
ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot'
ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*"
fi
# Activar la partición.
ogSetPartitionActive $1 $2
reboot
fi
fi
;;
MacOS)
# Modo de arranque por reinicio.
# Nota: el cliente tiene que tener configurado correctamente Grub.
touch ${MNTDIR}/boot.mac &>/dev/null
reboot
;;
GrubLoader)
# Reiniciar.
#reboot
;;
*) ogRaiseError $OG_ERR_NOTOS "$1 $2 ${TYPE:+($TYPE)}"
return $?
;;
esac
}
#/**
# ogGetWindowsName int_ndisk int_nfilesys
#@brief Muestra el nombre del equipo en el registro de Windows.
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@return str_name - nombre del equipo
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Adaptación para OpenGnSys.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2009-09-23
#*/ ##
function ogGetWindowsName ()
{
# Variables locales.
local MNTDIR
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
"$FUNCNAME 1 1 ==> PRACTICA-PC"
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Montar el sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
# Obtener dato del valor de registro.
ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
}
#/**
# ogLinuxBootParameters int_ndisk int_nfilesys
#@brief Muestra los parámetros de arranque de un sistema de archivos Linux.
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@return str_kernel str_initrd str_parameters ...
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@warning Función básica usada por \c ogBoot
#@version 0.9 - Primera adaptación para OpenGnSys.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2009-09-11
#@version 0.9.2 - Soporta partición /boot independiente.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2010-07-20
#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2013-05-14
#@version 1.0.6 - Detectar instalaciones sobre EFI.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2014-09-15
#*/ ##
function ogLinuxBootParameters ()
{
# Variables locales.
local MNTDIR CONFDIR CONFFILE f
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
"$FUNCNAME 1 2 ==> /vmlinuz-3.5.0-21-generic /initrd.img-3.5.0-21-generic root=/dev/sda2 ro splash"
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Detectar id. de tipo de partición y codificar al mnemonico.
MNTDIR=$(ogMount $1 $2) || return $?
# Fichero de configuración de GRUB.
CONFDIR=$MNTDIR # Sistema de archivos de arranque (/boot).
[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot # Sist. archivos raíz con directorio boot.
for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{2,},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do
[ -r $f ] && CONFFILE=$f
done
[ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
# Toma del fichero de configuracion los valores del kernel, initrd
# y parámetros de arranque usando las cláusulas por defecto
# ("default" en GRUB1, "set default" en GRUB2)
# y los formatea para que sean compatibles con \c kexec . */
# /* (comentario Doxygen)
awk 'BEGIN {cont=-1;}
$1~/^default$/ {sub(/=/," "); def=$2;}
$1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3;
if (def ~ /saved_entry/) def=0;
}
$1~/^(title|menuentry)$/ {cont++}
$1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; }
$1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) {
kern=$2;
sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0
} # /* (comentario Doxygen)
}
$1~/^initrd(16|efi)?$/ {if (def==cont) init=$2}
END {if (kern!="") printf("%s %s %s", kern,init,app)}
' $CONFFILE
# */ (comentario Doxygen)
}
#/**
# ogSetWindowsName int_ndisk int_nfilesys str_name
#@brief Establece el nombre del equipo en el registro de Windows.
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@param str_name nombre asignado
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
#@version 0.9 - Adaptación a OpenGnSys.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2009-09-24
#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2013-03-20
#*/ ##
function ogSetWindowsName ()
{
# Variables locales.
local PART MNTDIR NAME
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
"$FUNCNAME 1 1 PRACTICA-PC"
return
fi
# Error si no se reciben 3 parámetros.
[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Error si el nombre supera los 15 caracteres.
[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
# Montar el sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
# Asignar nombre.
NAME="$3"
# Modificar datos de los valores de registro.
ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\HostName' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV HostName' "$NAME" 2>/dev/null
ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
}
#/**
# ogSetWinlogonUser int_ndisk int_npartition str_username
#@brief Establece el nombre de usuario por defecto en la entrada de Windows.
#@param int_ndisk nº de orden del disco
#@param int_npartition nº de orden de la partición
#@param str_username nombre de usuario por defecto
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9.2 - Adaptación a OpenGnSys.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2010-07-20
#*/ ##
function ogSetWinlogonUser ()
{
# Variables locales.
local PART MNTDIR NAME
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
"$FUNCNAME 1 1 USUARIO"
return
fi
# Error si no se reciben 3 parámetros.
[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Montar el sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
# Asignar nombre.
NAME="$3"
# Modificar datos en el registro.
ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
}
#/**
# ogBootMbrXP int_ndisk
#@brief Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
#@param int_ndisk nº de orden del disco
#@return salida del programa my-sys
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Adaptación a OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2009-09-24
#*/ ##
function ogBootMbrXP ()
{
# Variables locales.
local DISK
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
"$FUNCNAME 1"
return
fi
# Error si no se recibe 1 parámetro.
[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
DISK="$(ogDiskToDev $1)" || return $?
ms-sys -z -f $DISK
ms-sys -m -f $DISK
}
#/**
# ogBootMbrGeneric int_ndisk
#@brief Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
#@param int_ndisk nº de orden del disco
#@return salida del programa my-sys
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Adaptación a OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2009-09-24
#*/ ##
function ogBootMbrGeneric ()
{
# Variables locales.
local DISK
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
"$FUNCNAME 1 "
return
fi
# Error si no se recibe 1 parámetro.
[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
DISK="$(ogDiskToDev $1)" || return $?
ms-sys -z -f $DISK
ms-sys -s -f $DISK
# Firma necesaria para Windows equipos UEFI
SIGNATURE=0x$(cat /proc/sys/kernel/random/uuid | cut -d '-' -f1)
ms-sys -S $SIGNATURE $DISK
}
#/**
# ogFixBootSector int_ndisk int_parition
#@brief Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
#@param int_ndisk nº de orden del disco
#@param int_partition nº de particion
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Adaptación a OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2009-09-24
#*/ ##
function ogFixBootSector ()
{
# Variables locales.
local PARTYPE DISK PART FILE
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
"$FUNCNAME 1 1 "
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
#TODO, solo si la particion existe
#TODO, solo si es ntfs o fat
PARTYPE=$(ogGetPartitionId $1 $2)
case "$PARTYPE" in
1|4|6|7|b|c|e|f|17|700|EF00)
;;
*)
return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
;;
esac
ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
#Preparando instruccion
let DISK=$1-1
PART=$2
FILE=/tmp/temp$$
cat > $FILE <<EOF
disk=$DISK
main_part=$PART
fix_first_sector=yes
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -a -f $FILE
rm -f $FILE
}
#/**
# ogGetBootMbr int_ndisk
#@brief Obtiene el contenido del sector de arranque de un disco.
#@param int_ndisk nº de orden del disco
#@return str_MBR Descripción del contenido del MBR.
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Dispositivo de disco no encontrado.
#@version 1.1.1b - Primera versión
#@author Irina Gómez (US). Propuesto por Antonio J. Doblas Viso (UMA)
#@date 2020-04-05
#*/ ##
function ogGetBootMbr ()
{
# Variables locales.
local DISK
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
"$FUNCNAME 1"
return
fi
# Error si no se recibe 1 parámetro.
[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndisk" || return $?
DISK="$(ogDiskToDev $1)" || return $?
ms-sys -f $DISK
}
#/**
# ogWindowsBootParameters int_ndisk int_parition
#@brief Configura el gestor de arranque de windows 7 / vista / XP / 2000
#@param int_ndisk nº de orden del disco
#@param int_partition nº de particion
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Integración desde EAC para OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2009-09-24
#@version 1.0.1 - Adapatacion para OpenGnsys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2011-05-20
#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2014-01-28
#@version 1.1.0 - Soporte para Windows 10.
#@author Ramon Gomez, ETSII Universidad de Sevilla
#@date 2016-01-19
#@version 1.1.1 - Compatibilidad con UEFI (ticket #802 #889)
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-01-28
#*/ ##
function ogWindowsBootParameters ()
{
# Variables locales.
local PART DISK BOOTLABEL BCDFILE BOOTDISK BOOTPART FILE WINVER MOUNT
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
"$FUNCNAME 1 1 "
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
#Preparando variables adaptadas a sintaxis windows.
let DISK=$1-1
PART=$2
FILE=/tmp/temp$$
if ogIsEfiActive; then
read BOOTDISK BOOTPART <<< $(ogGetEsp)
ogUnmount $BOOTDISK $BOOTPART || ogRaiseError $OG_ERR_PARTITION "ESP: $BOOTDISK $BOOTPART" || return $?
let BOOTDISK=$BOOTDISK-1
BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2)
BCDFILE="boot_BCD_file=/EFI/$BOOTLABEL/Boot/BCD"
else
BOOTDISK=$DISK
BOOTPART=$PART
BCDFILE=""
fi
# Obtener versión de Windows.
WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}')
[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?)
# Acciones para Windows XP.
if [[ "$WINVER" =~ "XP" ]]; then
MOUNT=$(ogMount $1 $2)
[ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?)
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
return 0
fi
ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
#Preparando instruccion Windows Resume Application
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$DISK
main_part=$PART
boot_entry=Windows Resume Application
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
#Preparando instruccion tipo windows
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$DISK
main_part=$PART
boot_entry=$WINVER
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
##Preparando instruccion Ramdisk Options
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$DISK
main_part=$PART
boot_entry=Ramdisk Options
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
##Preparando instruccion Recovery Environment
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$DISK
main_part=$PART
boot_entry=Windows Recovery Environment
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
##Preparando instruccion Recovery
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$DISK
main_part=$PART
boot_entry=Windows Recovery
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
#Preparando instruccion Windows Boot Manager
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$BOOTDISK
main_part=$BOOTPART
boot_entry=Windows Boot Manager
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$BOOTDISK
main_part=$BOOTPART
boot_entry=Herramienta de diagnóstico de memoria de Windows
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
cat > $FILE <<EOF
boot_disk=$BOOTDISK
boot_main_part=$BOOTPART
$BCDFILE
disk=$BOOTDISK
main_part=$BOOTPART
boot_entry=Herramienta de diagn<f3>stico de memoria de Windows
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -w -f $FILE
rm -f $FILE
}
#/**
# ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
#@brief Registra una partición en windows con un determinado volumen.
#@param int_ndisk nº de orden del disco a registrar
#@param int_partition nº de particion a registrar
#@param str_volumen volumen a resgistar
#@param int_ndisk_windows nº de orden del disco donde esta windows
#@param int_partition_windows nº de particion donde esta windows
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 0.9 - Adaptación a OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Málaga
#@date 2009-09-24
#*/ ##
function ogWindowsRegisterPartition ()
{
# Variables locales.
local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
"$FUNCNAME 1 1 c: 1 1"
return
fi
# Error si no se reciben 5 parámetros.
[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
REGISTREDDISK=$1
REGISTREDPART=$2
REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
DISK=$4
PART=$5
FILE=/tmp/temp$$
ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
VERSION=$(ogGetOsVersion $DISK $PART)
#Systemroot
if ogGetPath $DISK $PART WINDOWS
then
SYSTEMROOT="Windows"
elif ogGetPath $DISK $PART WINNT
then
SYSTEMROOT="winnt"
else
return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
fi
ogUnmount $DISK $PART
let DISK=$DISK-1
let REGISTREDDISK=$REGISTREDDISK-1
#Preparando instruccion Windows Boot Manager
cat > $FILE <<EOF
windows_disk=$DISK
windows_main_part=$PART
windows_dir=$SYSTEMROOT
disk=$REGISTREDDISK
main_part=$REGISTREDPART
;ext_part
part_letter=$REGISTREDVOL
EOF
timeout --foreground --signal=SIGKILL 5s spartlnx.run -cui -nm -u -f $FILE
}
#/**
# ogGrubInstallMbr int_disk_GRUBCFG int_partition_GRUBCFG
#@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.
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default]
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@version 1.0.2 - Primeras pruebas.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2011-10-29
#@version 1.0.3 - Soporte para linux de 32 y 64 bits
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2012-03-13
#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2012-03-13
#@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.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2017-06-19
#@version 1.1.0 - #827 Entrada para el ogLive si el equipo tiene partición cache.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2018-01-21
#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-01-08
#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-03-05
#*/ ##
function ogGrubInstallMbr ()
{
# Variables locales.
local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB GRUBENTRY NEWORDER
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage \"param param \" " \
"$FUNCNAME 1 1 FALSE " \
"$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
return
fi
# Error si no se reciben 2 parámetros.
[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
DISK=$1; PART=$2;
CHECKOS=${3:-"FALSE"}
KERNELPARAM=$4
BACKUPNAME=".backup.og"
#Error si no es linux.
#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
#VERSION=$(ogGetOsVersion $DISK $PART)
#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
#La primera etapa del grub se fija en el primer disco duro
FIRSTSTAGE=$(ogDiskToDev 1)
#localizar disco segunda etapa del grub
SECONDSTAGE=$(ogMount "$DISK" "$PART") || return $?
# prepara el directorio principal de la segunda etapa
[ -d ${SECONDSTAGE}/boot/grub/ ] || mkdir -p ${SECONDSTAGE}/boot/grub/
#Localizar directorio segunda etapa del grub
PREFIXSECONDSTAGE="/boot/grubMBR"
# Instalamos grub para EFI en ESP
EFIOPTGRUB=""
if ogIsEfiActive; then
read EFIDISK EFIPART <<< $(ogGetEsp)
# Comprobamos que exista ESP y el directorio para ubuntu
EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
if [ $? -ne 0 ]; then
ogFormat $EFIDISK $EFIPART FAT32
EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
fi
EFISUBDIR="grub"
# Borramos la configuración anterior
[ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
fi
# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
then
# Si no se reconfigura se utiliza el grub.cfg orginal
[ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
# Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
[ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] && rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
PREFIXSECONDSTAGE=""
else
# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
#llamada a updateBootCache para que aloje la primera fase del ogLive
updateBootCache
if ogIsEfiActive; then
# UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
[ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
fi
else
#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
fi
#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
#Preparar configuración segunda etapa: crear ubicacion
mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores)
sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
# (ogLive 5.0) Si 'pkgdatadir' está vacía ponemos valor de otros ogLive
sed -i '/grub-mkconfig_lib/i\pkgdatadir=${pkgdatadir:-"${datarootdir}/grub"}' /etc/grub.d/00_header
/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
#Preparar configuración segunda etapa: crear entrada del sistema operativo
grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
# Renombramos la configuración de grub antigua
[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
fi
#Instalar el grub
grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
EVAL=$?
# Movemos el grubx64.efi
if ogIsEfiActive; then
mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi
# Nombre OpenGnsys para cargador
cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi}
# Creamos entrada NVRAM y la ponemos en segundo lugar
ogNvramAddEntry grub /EFI/grub/Boot/shimx64.efi
GRUBENTRY=$(ogNvramList| awk '{if ($2=="grub") print $1}')
NEWORDER="$(ogNvramGetOrder|awk -v ENTRY=$GRUBENTRY '{gsub(",", " "); printf "%x %x %s\n", $1 , ENTRY , substr($0, index($0,$2))}')"
ogNvramSetOrder $NEWORDER
fi
return $EVAL
}
#/**
# ogGrubInstallPartition int_disk_SECONDSTAGE int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
#@brief Instala y actualiza el gestor grub en el bootsector de la particion indicada
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default]
#@param str "kernel param "
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@version 1.0.2 - Primeras pruebas.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2011-10-29
#@version 1.0.3 - Soporte para linux de 32 y 64 bits
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2012-03-13
#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2012-03-13
#@version 1.1.1 - #802 Equipos EFI: Se crea el grub.cfg de la partición EFI
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-01-08
#@version 1.1.1 - #890 UEFI: el grub.cfg original es necesario para obtener los datos del kernel efi: se mueve al final.
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-03-05
#*/ ##
function ogGrubInstallPartition ()
{
# Variables locales.
local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB EFIBOOTDIR
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage \"param param \" " \
"$FUNCNAME 1 1 FALSE " \
"$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
return
fi
# Error si no se reciben 2 parámetros.
[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
DISK=$1; PART=$2;
CHECKOS=${3:-"FALSE"}
KERNELPARAM=$4
BACKUPNAME=".backup.og"
#error si no es linux.
VERSION=$(ogGetOsVersion $DISK $PART)
echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
#Localizar primera etapa del grub
FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
#localizar disco segunda etapa del grub
SECONDSTAGE=$(ogMount $DISK $PART)
#Localizar directorio segunda etapa del grub
PREFIXSECONDSTAGE="/boot/grubPARTITION"
# Si es EFI instalamos el grub en la ESP
EFIOPTGRUB=""
# Desde el bootdir uefi y bios buscan el grub.cfg en subdirectorios distintos.
EFIBOOTDIR=""
if ogIsEfiActive; then
read EFIDISK EFIPART <<< $(ogGetEsp)
# Comprobamos que exista ESP y el directorio para ubuntu
EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART)
if [ $? -ne 0 ]; then
ogFormat $EFIDISK $EFIPART FAT32
EFISECONDSTAGE=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "ESP" || return $?
fi
EFISUBDIR=$(printf "Part-%02d-%02d" $DISK $PART)
# Borramos la configuración anterior
[ -d ${EFISECONDSTAGE}/EFI/$EFISUBDIR ] && rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR
mkdir -p ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
EFIOPTGRUB=" --removable --no-nvram --uefi-secure-boot --target $(ogGetArch)-efi --efi-directory=${EFISECONDSTAGE}/EFI/$EFISUBDIR "
EFIBOOTDIR="/boot"
fi
# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
if [ "${CHECKOS^^}" == "FALSE" ] && [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
then
# Si no se reconfigura se utiliza el grub.cfg orginal
[ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
# Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
[ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] && rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
# Reactivamos el grub con el grub.cfg original.
PREFIXSECONDSTAGE=""
else
# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
if ogIsEfiActive; then
# UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.
if ! [ -f ${SECONDSTAGE}/boot/grub/grub.cfg ]; then
[ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
fi
else
#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
fi
#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
#Preparar configuración segunda etapa: crear ubicacion
mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores)
sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header
# (ogLive 5.0) Si 'pkgdatadir' está vacía ponemos valor de otros ogLive
sed -i '/grub-mkconfig_lib/i\pkgdatadir=${pkgdatadir:-"${datarootdir}/grub"}' /etc/grub.d/00_header
/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null
#Preparar configuración segunda etapa: crear entrada del sistema operativo
grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
fi
#Instalar el grub
grub-install --force ${EFIOPTGRUB} --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
EVAL=$?
# Movemos el grubx64.efi
if ogIsEfiActive; then
mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot
rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI
cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi
# Nombre OpenGnsys para cargador
cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi}
fi
return $EVAL
}
#/**
# ogConfigureFstab int_ndisk int_nfilesys
#@brief Configura el fstab según particiones existentes
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND No se encuentra el fichero fstab a procesar.
#@warning Puede haber un error si hay más de 1 partición swap.
#@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2013-03-21
#@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2016-11-03
#@version 1.1.1 - Se configura la partición ESP (para sistemas EFI) (ticket #802)
#@author Irina Gómez, ETSII Universidad de Sevilla
#@date 2018-12-13
#*/ ##
function ogConfigureFstab ()
{
# Variables locales.
local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
local EFIDISK EFIPART EFIDEV EFIOPT
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
"$FUNCNAME 1 1"
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Error si no se encuentra un fichero etc/fstab en el sistema de archivos.
FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
# Hacer copia de seguridad del fichero fstab original.
cp -a ${FSTAB} ${FSTAB}.backup
# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
PARTROOT=$(ogDiskToDev $1 $2)
# Configuración de swap (solo 1ª partición detectada).
PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
if [ -n "$PARTSWAP" ]
then
# Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
if [ -n "$DEFSWAP" ]
then
echo "Hay definicion de SWAP en el FSTAB $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP" # Mensaje temporal.
sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
else
echo "No hay definicion de SWAP y si hay partición SWAP -> moficamos fichero" # Mensaje temporal.
sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
echo "$PARTSWAP none swap sw 0 0" >> ${FSTAB}
fi
else
echo "No hay partición SWAP -> configuramos FSTAB" # Mensaje temporal.
sed "/swap/d" ${FSTAB}.backup > ${FSTAB}
fi
# Si es un sistema EFI incluimos partición ESP (Si existe la modificamos)
if ogIsEfiActive; then
read EFIDISK EFIPART <<< $(ogGetEsp)
EFIDEV=$(ogDiskToDev $EFIDISK $EFIPART)
# Opciones de la partición ESP: si no existe ponemos un valor por defecto
EFIOPT=$(awk '$1!~/#/ && $2=="/boot/efi" {print $3"\t"$4"\t"$5"\t"$6 }' ${FSTAB})
[ "$EFIOPT" == "" ] && EFIOPT='vfat\tumask=0077\t0\t1'
sed -i /"boot\/efi"/d ${FSTAB}
echo -e "$EFIDEV\t/boot/efi\t$EFIOPT" >> ${FSTAB}
fi
}
#/**
# ogSetLinuxName int_ndisk int_nfilesys [str_name]
#@brief Establece el nombre del equipo en los ficheros hostname y hosts.
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@param str_name nombre asignado (opcional)
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@note Si no se indica nombre, se asigna un valor por defecto.
#@version 1.0.5 - Primera versión para OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2013-03-21
#*/ ##
function ogSetLinuxName ()
{
# Variables locales.
local MNTDIR ETC NAME
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
"$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
return
fi
# Error si no se reciben 2 o 3 parámetros.
case $# in
2) # Asignar nombre automático (por defecto, "pc").
NAME="$(ogGetHostname)"
NAME=${NAME:-"pc"} ;;
3) # Asignar nombre del 3er parámetro.
NAME="$3" ;;
*) # Formato de ejecución incorrecto.
ogRaiseError $OG_ERR_FORMAT
return $?
esac
# Montar el sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
ETC=$(ogGetPath $1 $2 /etc)
if [ -d "$ETC" ]; then
#cambio de nombre en hostname
echo "$NAME" > $ETC/hostname
#Opcion A para cambio de nombre en hosts
#sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
#Opcion B componer fichero de hosts
cat > $ETC/hosts <<EOF
127.0.0.1 localhost
127.0.1.1 $NAME
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
EOF
fi
}
#/**
# ogCleanLinuxDevices int_ndisk int_nfilesys
#@brief Limpia los dispositivos del equipo de referencia. Interfaz de red ...
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@version 1.0.5 - Primera versión para OpenGnSys.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2013-03-21
#@version 1.0.6b - Elimina fichero resume de hibernacion
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2016-11-07
#*/ ##
function ogCleanLinuxDevices ()
{
# Variables locales.
local MNTDIR
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
"$FUNCNAME 1 1"
return
fi
# Error si no se reciben 2 parámetros.
[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
# Montar el sistema de archivos.
MNTDIR=$(ogMount $1 $2) || return $?
# Eliminar fichero de configuración de udev para dispositivos fijos de red.
[ -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules ] && rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
# Eliminar fichero resume (estado previo de hibernación) utilizado por el initrd scripts-premount
[ -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume ] && rm -f ${MNTDIR}/etc/initramfs-tools/conf.d/resume
}
#/**
# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ]
#@brief Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente.
#@param 1 Numero de disco
#@param 2 Numero de particion
#@param 3 timeout Segundos de espera para iniciar el sistema operativo por defecto (opcional)
#@param 4 offline configura el modo offline [offline|online] (opcional)
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND No existe kernel o initrd en cache.
#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
# /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos.
#@version 1.0.6 - Prmera integración
#@author
#@date 2016-11-07
#@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.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2017-06-17
#*/ ##
function ogGrubAddOgLive ()
{
local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ time_out ] [ offline|online ] " \
"$FUNCNAME 1 1" \
"$FUNCNAME 1 6 15 offline"
return
fi
# Error si no se reciben 2 parámetros.
[ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ timeout ]"; echo $?)
[[ "$3" =~ ^[0-9]*$ ]] && TIMEOUT="$3"
# Error si no existe el kernel y el initrd en la cache.
# Falta crear nuevo codigo de error.
[ -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 $?)
# Archivo de configuracion del grub
DIRMOUNT=$(ogMount $1 $2)
GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
# Error si no existe archivo del grub
[ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$GRUBGFC" 1>&2; echo $?)
# Si existe la entrada de opengnsys, se borra
grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC
# Tipo de tabla de particiones
PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
# Localizacion de la cache
read NUMDISK NUMPART <<< $(ogFindCache)
let NUMDISK=$NUMDISK-1
# kernel y sus opciones. Pasamos a modo usuario
KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)"
# Configuracion offline si existe parametro
echo "$@" |grep offline &>/dev/null && STATUS=offline
echo "$@" |grep online &>/dev/null && STATUS=online
[ -z "$STATUS" ] || KERNEL="$(echo $KERNEL | sed s/"ogprotocol=[a-z]* "/"ogprotocol=local "/g ) ogstatus=$STATUS"
# Numero de línea de la primera entrada del grub.
NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1)
# Texto de la entrada de opengnsys
MENUENTRY="menuentry "OpenGnsys" --class opengnsys --class gnu --class os { \n \
\tinsmod part_$PARTTABLETYPE \n \
\tinsmod ext2 \n \
\tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \
\tlinux $KERNEL \n \
\tinitrd /boot/${oglivedir}/oginitrd.img \n \
}"
# Insertamos la entrada de opengnsys antes de la primera entrada existente.
sed -i "${NUMLINE}i\ $MENUENTRY" $GRUBGFC
# Ponemos que la entrada por defecto sea la primera.
sed -i s/"set.*default.*$"/"set default=\"0\""/g $GRUBGFC
# Si me dan valor para timeout lo cambio en el grub.
[ $TIMEOUT ] && sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC
}
#/**
# ogGrubHidePartitions num_disk num_part
#@brief ver ogBootLoaderHidePartitions
#@see ogBootLoaderHidePartitions
#*/ ##
function ogGrubHidePartitions ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ num_disk_partdata num_partdata ]" \
"$FUNCNAME 1 2" \
"$FUNCNAME 1 2 1 3"
return
fi
ogBootLoaderHidePartitions $@
return $?
}
#/**
# ogBurgHidePartitions num_disk num_part
#@brief ver ogBootLoaderHidePartitions
#@see ogBootLoaderHidePartitions
#*/ ##
function ogBurgHidePartitions ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [ num_disk_partdata num_partdata ]" \
"$FUNCNAME 1 2" \
"$FUNCNAME 1 2 1 3"
return
fi
ogBootLoaderHidePartitions $@
return $?
}
#/**
# ogBootLoaderHidePartitions num_disk num_part
#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando.
#@param 1 Numero de disco
#@param 2 Numero de particion
#@param 3 Numero de disco de la partición de datos (no ocultar)
#@param 4 Numero de particion de datos (no ocultar)
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception No existe archivo de configuracion del grub/burg.
#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg)
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2015-11-17
#@version 1.1 Se generaliza la función para grub y burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2017-10-20
#@version 1.1.1 Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
#@author Antonio J. Doblas Viso, EVLT Univesidad de Malaga.
#@date 2018-07-05
#@version Se permite una partición de datos que no se ocultará. Soporta más de un disco. Compatible con grub.cfg creado por ogLive 5.0
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-08-26
#*/
function ogBootLoaderHidePartitions ()
{
local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY WINPART ENTRY LINE PART PARTDATA TEXT PARTHIDDEN HIDDEN
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions"
return
fi
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 2 parámetros.
[ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part [ num_disk_partdata num_partdata ]"; echo $?)
# Si no existe $4 pongo un valor imposible para la partición de datos
[ $# -eq 4 ] && PARTDATA=$(ogDiskToDev $3 $4) || PARTDATA=0
# Archivo de configuracion del grub
DIRMOUNT=$(ogMount $1 $2)
# La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions.
case "$FUNC" in
ogGrubHidePartitions)
CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
;;
ogBurgHidePartitions)
CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions."
return $?
;;
esac
# Error si no existe archivo del grub
[ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$CFGFILE" 1>&2; echo $?)
# Si solo hay una particion de Windows me salgo
[ $(fdisk -l $(ogDiskToDev) | grep 'NTFS' |wc -l) -eq 1 ] && return 0
# Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion.
sed -i '/parttool/d' $CFGFILE
PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:])
# /* (comentario de bloque para Doxygen)
# Entradas de Windows: numero de linea y particion. De mayor a menor.
WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, ""); gsub(/^.*dev/,""); print NR":/dev"$1} ' $CFGFILE | sed -e '1!G;h;$!d')
#*/ (comentario para bloque Doxygen)
# Particiones de Windows, pueden no estar en el grub.
WINPART=$(fdisk -l $(ogDiskToDev)|awk '/NTFS/ {print $1}'|sed '1!G;h;$!d')
# Modifico todas las entradas de Windows.
for ENTRY in $WINENTRY; do
LINE=${ENTRY%:*}
PART=${ENTRY#*:}
# En cada entrada, oculto o muestro cada particion.
TEXT=""
for PARTHIDDEN in $WINPART; do
# Muestro la particion de la entrada actual y la de datos.
[ "$PARTHIDDEN" == "$PART" -o "$PARTHIDDEN" == "$PARTDATA" ] && HIDDEN="-" || HIDDEN="+"
read NUMDISK NUMPART <<< $(ogDevToDisk $PARTHIDDEN)
TEXT="\tparttool (hd$((NUMDISK-1)),$PARTTABLETYPE$NUMPART) hidden$HIDDEN \n$TEXT"
done
sed -i "${LINE}a\ $TEXT" $CFGFILE
done
# Activamos la particion que se inicia en todas las entradas de windows.
sed -i "/chainloader/i\\\tparttool \$\{root\} boot+" $CFGFILE
}
#/**
# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete
#@brief ver ogBootLoaderDeleteEntry
#@see ogBootLoaderDeleteEntry
#*/
function ogGrubDeleteEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
"$FUNCNAME 1 6 2 1"
return
fi
ogBootLoaderDeleteEntry $@
return $?
}
#/**
# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete
#@brief ver ogBootLoaderDeleteEntry
#@see ogBootLoaderDeleteEntry
#*/
function ogBurgDeleteEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \
"$FUNCNAME 1 6 2 1"
return
fi
ogBootLoaderDeleteEntry $@
return $?
}
#/**
# ogRefindDeleteEntry num_disk_delete num_part_delete
#@brief ver ogBootLoaderDeleteEntry
#@see ogBootLoaderDeleteEntry
#*/
function ogRefindDeleteEntry ()
{
local EFIDISK EFIPART
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_disk_delete int_npartition_delete" \
"$FUNCNAME 2 1"
return
fi
read EFIDISK EFIPART <<< $(ogGetEsp)
ogBootLoaderDeleteEntry $EFIDISK $EFIPART $@
return $?
}
#/**
# ogBootLoaderDeleteEntry num_disk num_part num_part_delete
#@brief Borra en el grub las entradas para el inicio en una particion.
#@param 1 Numero de disco donde esta el grub
#@param 2 Numero de particion donde esta el grub
#@param 3 Numero del disco del que borramos las entradas
#@param 4 Numero de la particion de la que borramos las entradas
#@note Tiene que ser llamada desde ogGrubDeleteEntry, ogBurgDeleteEntry o ogRefindDeleteEntry
#@return (nada)
#@exception OG_ERR_FORMAT Use ogGrubDeleteEntry or ogBurgDeleteEntry.
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub.
#@version 1.1 Se generaliza la función para grub y burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2017-10-20
#*/ ##
function ogBootLoaderDeleteEntry ()
{
local FUNC DIRMOUNT CFGFILE LABEL MENUENTRY DELETEENTRY ENDENTRY ENTRY
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry, ogGrubDeleteEntry or ogRefindDeleteEntry"
return
fi
# Si el número de parámetros menos que 4 nos salimos
[ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?)
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Archivo de configuracion del grub
DIRMOUNT=$(ogMount $1 $2)
# La función debe ser llamanda desde ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry.
case "$FUNC" in
ogGrubDeleteEntry)
CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
;;
ogBurgDeleteEntry)
CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
;;
ogRefindDeleteEntry)
CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry."
return $?
;;
esac
# Dispositivo
if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
LABEL=$(printf "Part-%02d-%02d" $3 $4)
else
LABEL=$(ogDiskToDev $3 $4)
fi
# Error si no existe archivo de configuración
[ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Numero de linea de cada entrada.
MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )"
# Entradas que hay que borrar.
DELETEENTRY=$(grep -n menuentry.*$LABEL $CFGFILE| cut -d: -f1)
# Si no hay entradas para borrar me salgo con aviso
[ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $LABEL" || return $?
# Recorremos el fichero del final hacia el principio.
ENDENTRY="$(wc -l $CFGFILE|cut -d" " -f1)"
for ENTRY in $MENUENTRY; do
# Comprobamos si hay que borrar la entrada.
if ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then
let ENDENTRY=$ENDENTRY-1
sed -i -e $ENTRY,${ENDENTRY}d $CFGFILE
fi
# Guardamos el número de línea de la entrada, que sera el final de la siguiente.
ENDENTRY=$ENTRY
done
}
#/**
# ogBurgInstallMbr int_disk_GRUBCFG int_partition_GRUBCFG
#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default]
#@brief Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default]
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición no soportada
#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR.
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2017-06-23
#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2018-01-21
#@version 1.1.0 - Refactorizar fichero de configuacion
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2018-01-24
#@version 1.1.1 - Se incluye comentarios en codigo para autodocuemtnacion con Doxygen
#@author Antonio J. Doblas Viso. Universidad de Malaga.
#@date 2018-07-05
#*/ ##
function ogBurgInstallMbr ()
{
# Variables locales.
local BINARYAVAILABLE PART DISK DEVICE MOUNTDISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage \"param param \" " \
"$FUNCNAME 1 1 FALSE " \
"$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
return
fi
# Error si no se reciben 2 parametros.
[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
#Error si no tenemos el binario burg
BINARYAVAILABLE=$(burg-install -v &>/dev/null && echo "YES" ||echo "NO")
if [ "$BINARYAVAILABLE" == NO ]; then
if [ -e $OGLIB/burg/burg.tgz ]; then
cd / ; tar xzvf $OGLIB/burg/burg.tgz --strip 1 &>/dev/null
else
return $(ogRaiseError $OG_ERR_NOTEXEC "Binary burg not found"; echo $?)
fi
fi
DISK=$1; PART=$2;
CHECKOS=${3:-"FALSE"}
KERNELPARAM=$4
BACKUPNAME=".backup.og"
#Controlar disco no uefi
ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?)
#Controlar particionado tipo msdos
ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?)
#Controlar existencia de disco y particion
DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $?
MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $?
#Controlar particion segunda etapa del burg
ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg.cfg soporta solo particiones linux"; echo $?)
#Controlar acceso de escritura a la particion segunda etapa del burg
ogIsReadonly $DISK $PART && return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?)
#Asigar la primera etapa del grub en el primer disco duro
FIRSTSTAGE=$(ogDiskToDev 1)
#Localizar disco segunda etapa del grub
SECONDSTAGE=$(ogMount $DISK $PART)
#Preparar el directorio principal de la segunda etapa (y copia los binarios)
[ -d ${SECONDSTAGE}/boot/burg/ ] || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/themes ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; #*/ ## (comentario Dogygen) #*/ ## (comentario Dogygen)
#Copiar el tema de opengnsys
mkdir -p ${SECONDSTAGE}/boot/burg/themes/OpenGnsys
cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null
# No configurar la segunda etapa (grub.cfg). Parámetro FALSE
if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ];
then
if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
then
burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
return $?
fi
fi
# Configurrar la segunda etapa (burg.cfg) == tercer parámetro TRUE
#llamar a updateBootCache para que aloje la primera fase del ogLive
updateBootCache
#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
#Preparar configuración segunda etapa: crear ubicacion
mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/
#Preparar configuración segunda etapa: crear cabecera del fichero
FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg
#/* ## (comentario Dogygen)
cat > "$FILECFG" << EOF
set theme_name=OpenGnsys
set gfxmode=1024x768
set locale_dir=(\$root)/boot/burg/locale
set default=0
set timeout=25
set lang=es
insmod ext2
insmod gettext
if [ -s \$prefix/burgenv ]; then
load_env
fi
if [ \${prev_saved_entry} ]; then
set saved_entry=\${prev_saved_entry}
save_env saved_entry
set prev_saved_entry=
save_env prev_saved_entry
set boot_once=true
fi
function savedefault {
if [ -z \${boot_once} ]; then
saved_entry=\${chosen}
save_env saved_entry
fi
}
function select_menu {
if menu_popup -t template_popup theme_menu ; then
free_config template_popup template_subitem menu class screen
load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
save_env theme_name
menu_refresh
fi
}
function toggle_fold {
if test -z $theme_fold ; then
set theme_fold=1
else
set theme_fold=
fi
save_env theme_fold
menu_refresh
}
function select_resolution {
if menu_popup -t template_popup resolution_menu ; then
menu_reload_mode
save_env gfxmode
fi
}
if test -f \${prefix}/themes/\${theme_name}/theme ; then
insmod coreui
menu_region.text
load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}'
load_config \${prefix}/themes/conf.d/10_hotkey
load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name}
insmod vbe
insmod png
insmod jpeg
set gfxfont="Unifont Regular 16"
menu_region.gfx
vmenu resolution_menu
controller.ext
fi
EOF
#*/ ## (comentario Dogygen)
#Preparar configuración segunda etapa: crear entrada del sistema operativo
grubSyntax "$KERNELPARAM" >> "$FILECFG"
#Instalar el burg
burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null
}
#/**
# ogGrubDefaultEntry int_disk_GRUGCFG int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry
#@brief ver ogBootLoaderDefaultEntry
#@see ogBootLoaderDefaultEntry
#*/ ##
function ogGrubDefaultEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
"$FUNCNAME 1 6 1 1"
return
fi
ogBootLoaderDefaultEntry $@
return $?
}
#/**
# ogBurgDefaultEntry int_disk_BURGCFG int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry
#@brief ver ogBootLoaderDefaultEntry
#@see ogBootLoaderDefaultEntry
#*/ ##
function ogBurgDefaultEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \
"$FUNCNAME 1 6 1 1"
return
fi
ogBootLoaderDefaultEntry $@
return $?
}
#/**
# ogRefindDefaultEntry int_disk_default_entry int_npartition_default_entry
#@brief ver ogBootLoaderDefaultEntry
#@see ogBootLoaderDefaultEntry
#*/ ##
function ogRefindDefaultEntry ()
{
local EFIDISK EFIPART
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_disk_default_entry int_npartition_default_entry" \
"$FUNCNAME 1 1"
return
fi
read EFIDISK EFIPART <<< $(ogGetEsp)
ogBootLoaderDefaultEntry $EFIDISK $EFIPART $@
return $?
}
#/**
# ogBootLoaderDefaultEntry int_disk_CFG int_partition_CFG int_disk_default_entry int_npartition_default_entry
#@brief Configura la entrada por defecto de Burg
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param int_disk_default_entry
#@param int_part_default_entry
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero.
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg.
#@version 1.1.0 - Define la entrada por defecto del Burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2017-08-09
#@version 1.1 Se generaliza la función para grub y burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2018-01-04
#*/ ##
function ogBootLoaderDefaultEntry ()
{
# Variables locales.
local PART FUNC DIRMOUNT LABEL CFGFILE DEFAULTENTRY MENUENTRY MSG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
return
fi
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 3 parametros.
[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $?
# Error si no puede montar sistema de archivos.
DIRMOUNT=$(ogMount $1 $2) || return $?
# Comprobamos que exista fichero de configuración
# La función debe ser llamanda desde ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry.
case "$FUNC" in
ogGrubDefaultEntry)
CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg"
;;
ogBurgDefaultEntry)
CFGFILE="$DIRMOUNT/boot/burg/burg.cfg"
;;
ogRefindDefaultEntry)
CFGFILE="$DIRMOUNT/EFI/refind/refind.conf"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry."
return $?
;;
esac
# Error si no existe archivo de configuración
[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Dispositivo
if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
LABEL=$(printf "Part-%02d-%02d" $3 $4)
else
LABEL=$(ogDiskToDev $3 $4)
fi
# Número de línea de la entrada por defecto en CFGFILE (primera de la partición).
DEFAULTENTRY=$(grep -n -m 1 menuentry.*$LABEL $CFGFILE| cut -d: -f1)
# Si no hay entradas para borrar me salgo con aviso
[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $LABEL" || return $?
# Número de la de linea por defecto en el menú de usuario
MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)"
if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
sed -i /default_selection.*$/d $CFGFILE
sed -i "1 i\default_selection $MENUENTRY" $CFGFILE
else
# En grub y burg las líneas empiezan a contar desde cero
let MENUENTRY=$MENUENTRY-1
sed --regexp-extended -i s/"set default=\"?[0-9]*\"?$"/"set default=\"$MENUENTRY\""/g $CFGFILE
fi
MSG="MSG_HELP_$FUNC"
echo "${!MSG%%\.}: $@"
}
#/**
# ogGrubOgliveDefaultEntry num_disk num_part
#@brief ver ogBootLoaderOgliveDefaultEntry
#@see ogBootLoaderOgliveDefaultEntry
#*/ ##
function ogGrubOgliveDefaultEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
"$FUNCNAME 1 6"
return
fi
ogBootLoaderOgliveDefaultEntry $@
return $?
}
#/**
# ogBurgOgliveDefaultEntry num_disk num_part
#@brief ver ogBootLoaderOgliveDefaultEntry
#@see ogBootLoaderOgliveDefaultEntry
#*/ ##
function ogBurgOgliveDefaultEntry ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \
"$FUNCNAME 1 6"
return
fi
ogBootLoaderOgliveDefaultEntry $@
return $?
}
#/**
# ogRefindOgliveDefaultEntry
#@brief ver ogBootLoaderOgliveDefaultEntry
#@see ogBootLoaderOgliveDefaultEntry
#*/ ##
function ogRefindOgliveDefaultEntry ()
{
local EFIDISK EFIPART
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME" \
"$FUNCNAME"
return
fi
read EFIDISK EFIPART <<< $(ogGetEsp)
ogBootLoaderOgliveDefaultEntry $EFIDISK $EFIPART
return $?
}
#/**
# ogBootLoaderOgliveDefaultEntry
#@brief Configura la entrada de ogLive como la entrada por defecto de Burg.
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg.
#@exception OG_ERR_NOTFOUND Entrada de OgLive no encontrada en burg.cfg.
#@version 1.1.0 - Primeras pruebas con Burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2017-08-09
#@version 1.1 Se generaliza la función para grub y burg
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2018-01-04
#*/ ##
function ogBootLoaderOgliveDefaultEntry ()
{
# Variables locales.
local FUNC PART CFGFILE NUMENTRY MSG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry" \
return
fi
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 2 parametros.
[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $1 $2) || return $?
# La función debe ser llamanda desde ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry.
case "$FUNC" in
ogGrubOgliveDefaultEntry)
CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
;;
ogBurgOgliveDefaultEntry)
CFGFILE="$PART/boot/burg/burg.cfg"
;;
ogRefindOgliveDefaultEntry)
CFGFILE="$PART/EFI/refind/refind.conf"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry."
return $?
;;
esac
# Comprobamos que exista fichero de configuración
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Detectamos cual es la entrada de ogLive
NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1)
# Si no existe entrada de ogLive nos salimos
[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?)
if [ "$(basename $CFGFILE)" == "refind.conf" ]; then
sed -i /default_selection.*$/d $CFGFILE
sed -i "1 i\default_selection $NUMENTRY" $CFGFILE
else
let NUMENTRY=$NUMENTRY-1
sed --regexp-extended -i s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE
fi
MSG="MSG_HELP_$FUNC"
echo "${!MSG%%\.}: $@"
}
#/**
# ogGrubSecurity int_disk_GRUBCFG int_partition_GRUBCFG [user] [password]
#@brief Configura grub.cfg para que sólo permita editar entrada o acceder a línea de comandos al usuario especificado
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param user (default root)
#@param password (default "", no puede entrar)
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar (ogMount).
#@exception OG_ERR_NOTFOUND No encuentra archivo de configuración del grub.
#@author Irina Gomez, ETSII Universidad de Sevilla
#@date 2019-12-17
#*/ ##
function ogGrubSecurity ()
{
# Variables locales.
local SECONDSTAGE GRUBGFC FILE USER PASSWD ENCRYPTPASSWD
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [USER] [PASSWORD]" \
"$FUNCNAME 1 1 " \
"$FUNCNAME 1 2 user clave"
return
fi
# Error si no se reciben 2 parámetros.
[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [USER] [PASSWORD]"|| return $?
#localizar disco segunda etapa del grub
SECONDSTAGE=$(ogMount "$1" "$2") || return $?
GRUBGFC=$(ls $SECONDSTAGE/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg,grub.cfg.backup.og} 2>/dev/null)
# comprobamos que exista el archivo de configuración.
[ -n "$GRUBGFC" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
USER=${3:-root}
PASSWD=${4:-""}
ENCRYPTPASSWD=$(echo -e "$PASSWD\n$PASSWD"|grub-mkpasswd-pbkdf2|sed -e 1,2d -e s/^.*grub/grub/)
for FILE in $GRUBGFC; do
# Eliminamos configuración anterior
sed -i -e /superusers/d -e /password_pbkdf2/d $FILE
# Configuramos grub.cfg para que sólo permita editar o entrar en línea de comandos al usuario especificado
[ "$PASSWD" == "" ] || sed -i "1i\password_pbkdf2 $USER $ENCRYPTPASSWD" $FILE
sed -i "1i\set superusers=\"$USER\"" $FILE
# Permitimos que se seleccionen las entradas
sed -i /"menuentry "/s/"{"/"--unrestricted {"/ $FILE
done
}
#/**
# ogGrubSetTheme num_disk num_part str_theme
#@brief ver ogBootLoaderSetTheme
#@see ogBootLoaderSetTheme
#*/ ##
function ogGrubSetTheme ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
"$FUNCNAME 1 4 ThemeBasic"\
"$FUNCNAME \$(ogFindCache) ThemeBasic"
return
fi
ogBootLoaderSetTheme $@
return $?
}
#/**
# ogBurgSetTheme num_disk num_part str_theme
#@brief ver ogBootLoaderSetTheme
#@see ogBootLoaderSetTheme
#*/ ##
function ogBurgSetTheme ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \
"$FUNCNAME 1 4 ThemeBasic" \
"$FUNCNAME \$(ogFindCache) ThemeBasic"
echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)"
return
fi
ogBootLoaderSetTheme $@
return $?
}
#/**
# ogRefindSetTheme str_theme
#@brief ver ogBootLoaderSetTheme
#@see ogBootLoaderSetTheme
#*/ ##
function ogRefindSetTheme () {
local PART DIRTHEME CFGFILE
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME str_themeName" \
"$FUNCNAME ThemeBasic"
echo -e "\nThemes in $OGLIB/refind:\n$(ls $OGLIB/refind/themes/ 2>/dev/null)"
return
fi
# Detectamos partición ESP
read EFIDISK EFIPART <<< $(ogGetEsp)
PART=$(ogMount $EFIDISK $EFIPART) || return $?
DIRTHEME="$PART/EFI/refind/themes"
CFGFILE="$PART/EFI/refind/refind.conf"
# Para utilizar ogBootLoaderSetTheme es necesario la entrada set theme_name
if [ -f $CFGFILE ]; then
sed -i '1 i\set theme_name=none' $CFGFILE
else
ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
fi
# Creamos el directorio para los temas
[ -d $DIRTHEME ] || mkdir $DIRTHEME
ogBootLoaderSetTheme $EFIDISK $EFIPART $@
return $?
}
#/**
# ogBootLoaderSetTheme
#@brief asigna un tema al BURG
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param str_theme_name
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg refind.conf.
#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg.
#@exception OG_ERR_NOTFOUND Fichero de configuración del tema no encontrado: theme.conf (sólo refind).
#@note El tema debe situarse en OGLIB/BOOTLOADER/themes
#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
#@author Antonio J. Doblas Viso. Universidad de Malaga
#@date 2018-01-24
#@version 1.1.1 - Soporta rEFInd (ticket #802 #888).
#@author Irina Gomez. Universidad de Sevilla
#@date 2019-03-22
#*/ ##
function ogBootLoaderSetTheme ()
{
# Variables locales.
local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG NEWTHEMECFG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
return
fi
NEWTHEME="$3"
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 3 parametros.
[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $1 $2) || return $?
# La función debe ser llamanda desde ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme.
case "$FUNC" in
ogGrubSetTheme)
BOOTLOADER="grub"
BOOTLOADERDIR="boot/grubMBR"
CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported"
return $?
;;
ogBurgSetTheme)
BOOTLOADER="burg"
BOOTLOADERDIR="boot/burg"
CFGFILE="$PART/boot/burg/burg.cfg"
;;
ogRefindSetTheme)
BOOTLOADER="refind"
BOOTLOADERDIR="EFI/refind"
CFGFILE="$PART/EFI/refind/refind.conf"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme, ogBurgSetTheme or ogRefindSetTheme."
return $?
;;
esac
# Comprobamos que exista fichero de configuración
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Detectamos cual es el tema asignado
THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2)
# Si no existe entrada de theme_name nos salimos
[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?)
#Actualizamos el tema del servidor a la particion
if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then
# Para refind es necesario que exista theme.conf en el directorio del tema.
if [ "$BOOTLOADER" == "refind" ]; then
NEWTHEMECFG="$OGLIB/$BOOTLOADER/themes/$NEWTHEME/theme.conf"
[ -f $NEWTHEMECFG ] || ogRaiserError $OG_ERR_NOTFOUND "theme.conf" || return $?
grep -v "^#" $NEWTHEMECFG >> $CFGFILE
# eliminamos "set theme" es de grub y no de refind
sed -i '/theme_name/d' $CFGFILE
fi
cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/$BOOTLOADERDIR/themes/
fi
#Verificamos que el tema esta en la particion
if ! [ -d $PART/$BOOTLOADERDIR/themes/$NEWTHEME ]; then
ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/$BOOTLOADERDIR/themes/" || return $?
fi
#Cambiamos la entrada el fichero de configuración.
sed --regexp-extended -i s/"set theme_name=$THEME"/"set theme_name=$NEWTHEME"/g $CFGFILE
}
#/**
# ogGrubSetAdminKeys num_disk num_part str_theme
#@brief ver ogBootLoaderSetTheme
#@see ogBootLoaderSetTheme
#*/ ##
function ogGrubSetAdminKeys ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
"$FUNCNAME 1 4 FALSE "\
"$FUNCNAME \$(ogFindCache) ThemeBasic"
return
fi
ogBootLoaderSetAdminKeys $@
return $?
}
#/**
# ogBurgSetAdminKeys num_disk num_part str_bolean
#@brief ver ogBootLoaderSetAdminKeys
#@see ogBootLoaderSetAdminKeys
#*/ ##
function ogBurgSetAdminKeys ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \
"$FUNCNAME 1 4 TRUE" \
"$FUNCNAME \$(ogFindCache) FALSE"
return
fi
ogBootLoaderSetAdminKeys $@
return $?
}
#/**
# ogBootLoaderSetAdminKeys
#@brief Activa/Desactica las teclas de administracion
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param Boolean TRUE/FALSE
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg.
#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg.
#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
#@author Antonio J. Doblas Viso. Universidad de Malaga
#@date 2018-01-24
#*/ ##
function ogBootLoaderSetAdminKeys ()
{
# Variables locales.
local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys"
return
fi
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 2 parametros.
[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $1 $2) || return $?
# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys.
case "$FUNC" in
ogGrubSetAdminKeys)
BOOTLOADER="grub"
BOOTLOADERDIR="grubMBR"
CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported"
return $?
;;
ogBurgSetAdminKeys)
BOOTLOADER="burg"
BOOTLOADERDIR="burg"
CFGFILE="$PART/boot/burg/burg.cfg"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys"
return $?
;;
esac
# Comprobamos que exista fichero de configuración
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
case "$3" in
true|TRUE)
[ -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
;;
false|FALSE)
[ -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
;;
*)
ogRaiseError $OG_ERR_FORMAT "str bolean unknow "
return $?
;;
esac
}
#/**
# ogGrubSetTimeOut num_disk num_part int_timeout_seconds
#@brief ver ogBootLoaderSetTimeOut
#@see ogBootLoaderSetTimeOut
#*/ ##
function ogGrubSetTimeOut ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \
"$FUNCNAME 1 4 50 "\
"$FUNCNAME \$(ogFindCache) 50"
return
fi
ogBootLoaderSetTimeOut $@
return $?
}
#/**
# ogBurgSetTimeOut num_disk num_part str_bolean
#@brief ver ogBootLoaderSetTimeOut
#@see ogBootLoaderSetTimeOut
#*/ ##
function ogBurgSetTimeOut ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \
"$FUNCNAME 1 4 50" \
"$FUNCNAME \$(ogFindCache) 50"
return
fi
ogBootLoaderSetTimeOut $@
return $?
}
#/**
# ogRefindSetTimeOut int_timeout_second
#@brief ver ogBootLoaderSetTimeOut
#@see ogBootLoaderSetTimeOut
#*/ ##
function ogRefindSetTimeOut ()
{
local EFIDISK EFIPART
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_timeout_seconds" \
"$FUNCNAME 50"
return
fi
read EFIDISK EFIPART <<< $(ogGetEsp)
ogBootLoaderSetTimeOut $EFIDISK $EFIPART $@
return $?
}
#/**
# ogBootLoaderSetTimeOut
#@brief Define el tiempo (segundos) que se muestran las opciones de inicio
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param int_timeout_seconds
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg.
#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg.
#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR
#@author Antonio J. Doblas Viso. Universidad de Malaga
#@date 2018-01-24
#*/ ##
function ogBootLoaderSetTimeOut ()
{
# Variables locales.
local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut"
return
fi
ogCheckStringInReg $3 "^[0-9]{1,10}$" && TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer"
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 3 parametros.
[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $1 $2) || return $?
# La función debe ser llamanda desde ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut.
case "$FUNC" in
ogGrubSetTimeOut)
BOOTLOADER="grub"
BOOTLOADERDIR="boot/grubMBR"
CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
;;
ogBurgSetTimeOut)
BOOTLOADER="burg"
BOOTLOADERDIR="boot/burg"
CFGFILE="$PART/boot/burg/burg.cfg"
;;
ogRefindSetTimeOut)
BOOTLOADER="refind"
BOOTLOADERDIR="EFI/refind"
CFGFILE="$PART/EFI/refind/refind.conf"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut."
return $?
;;
esac
# Comprobamos que exista fichero de configuración
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Asignamos el timeOut.
if [ "$BOOTLOADER" == "refind" ]; then
sed -i s/timeout.*$/"timeout $TIMEOUT"/g $CFGFILE
else
sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE
fi
}
#/**
# ogGrubSetResolution num_disk num_part int_resolution
#@brief ver ogBootLoaderSetResolution
#@see ogBootLoaderSetResolution
#*/ ##
function ogGrubSetResolution ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
"$FUNCNAME 1 4 1024x768" \
"$FUNCNAME \$(ogFindCache) 1024x768" \
"$FUNCNAME 1 4"
return
fi
ogBootLoaderSetResolution $@
return $?
}
#/**
# ogBurgSetResolution num_disk num_part str_bolean
#@brief ver ogBootLoaderSetResolution
#@see ogBootLoaderSetResolution
#*/ ##
function ogBurgSetResolution ()
{
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \
"$FUNCNAME 1 4 1024x768" \
"$FUNCNAME \$(ogFindCache) 1024x768" \
"$FUNCNAME 1 4"
return
fi
ogBootLoaderSetResolution $@
return $?
}
#/**
# ogBootLoaderSetResolution
#@brief Define la resolucion que usuara el thema del gestor de arranque
#@param int_disk_SecondStage
#@param int_part_SecondStage
#@param str_resolution (Opcional)
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg.
#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado.
#@author Antonio J. Doblas Viso. Universidad de Malaga
#@date 2018-01-24
#*/ ##
function ogBootLoaderSetResolution ()
{
# Variables locales.
local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution, ogBurgSetResolution or ogRefindSetResolution."
return
fi
# Nombre de la función que llama a esta.
FUNC="${FUNCNAME[@]:1}"
FUNC="${FUNC%%\ *}"
# Error si no se reciben 2 parametros.
[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $1 $2) || return $?
# La función debe ser llamanda desde ogGrugSetResolution, ogBurgSetResolution or ogRefindSetResolution.
case "$FUNC" in
ogGrubSetResolution)
BOOTLOADER="grub"
BOOTLOADERDIR="grubMBR"
CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg"
ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported"
return $?
;;
ogBurgSetResolution)
BOOTLOADER="burg"
BOOTLOADERDIR="burg"
CFGFILE="$PART/boot/burg/burg.cfg"
;;
*)
ogRaiseError $OG_ERR_FORMAT "Use GrugSetResolution, ogBurgSetResolution or ogRefindSetResolution."
return $?
;;
esac
DEFAULTRESOLUTION=1024x768
# Comprobamos que exista fichero de configuración
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
#controlar variable a consierar vga (default template) o video (menu)
#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto
if [ $# -eq 2 ] ; then
if [ -n $video ]; then
NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-)
fi
if [ -n $vga ] ; then
case "$vga" in
788|789|814)
NEWRESOLUTION=800x600
;;
791|792|824)
NEWRESOLUTION=1024x768
;;
355)
NEWRESOLUTION=1152x864
;;
794|795|829)
NEWRESOLUTION=1280x1024
;;
esac
fi
fi
if [ $# -eq 3 ] ; then
#comprobamos que el parametro 3 cumple formato NNNNxNNNN
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"
fi
# Si no existe NEWRESOLUCION asignamos la defaulT
[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION
#Cambiamos la entrada el fichero de configuración.
sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE
}
#/**
# ogBootLoaderSetResolution
#@brief Define la resolucion que usuara el thema del gestor de arranque
#@param int_resolution1
#@param int_resolution2 (Opcional)
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount).
#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg.
#*/ ##
function ogRefindSetResolution () {
local PART CFGFILE
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_resolution1 [int_resolution2]" \
"$FUNCNAME 1366 768" \
"$FUNCNAME 1"
return
fi
# Error si no se reciben 2 parametros.
[ $# -ge 1 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_resolution1 [int_resolution2]" || return $?
# Error si no puede montar sistema de archivos.
PART=$(ogMount $(ogGetEsp)) || return $?
# Comprobamos que exista fichero de configuración
CFGFILE=$PART/EFI/refind/refind.conf
[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $?
# Borramos resolucion anterior y configuramos la nueva
sed -i /^resolution/d $CFGFILE
sed -i "1 i\resolution $1 $2" $CFGFILE
}
# ogRefindInstall bool_autoconfig
#@brief Instala y actualiza el gestor rEFInd en la particion EFI
#@param bolean_Check__auto_config true | false[default]
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND No se encuentra la partición ESP.
#@exception OG_ERR_NOTFOUND No se encuentra shimx64.efi.signed.
#@exception OG_ERR_NOTFOUND No se encuentra refind-install o refind en OGLIB
#@exception OG_ERR_PARTITION No se puede montar la partición ESP.
#@note Refind debe estar instalado en el ogLive o compartido en OGLIB
#@version 1.1.0 - Primeras pruebas.
#@author Juan Carlos Garcia. Universidad de ZAragoza.
#@date 2017-06-26
#@version 1.1.1 - Usa refind-install. Obtiene partición con ogGetEsp. Configura Part-X-Y y ogLive.
#@author Irina Gomez. Universidad de Sevilla.
#@date 2019-03-22
#*/ ##
function ogRefindInstall () {
# Variables locales.
local CONFIG EFIDISK EFIPART EFIDEVICE EFIMNT EFIDIR SHIM REFINDDIR
local CACHEDEVICE OGLIVE OGLIVEDIR CMDLINE OGICON CFGFILE DEVICES
local LNXCFGFILE NUMENTRY DIR
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME boolean_autoconfig " \
"$FUNCNAME TRUE"
return
fi
# Recogemos parametros
CONFIG=${1:-"FALSE"}
read -e EFIDISK EFIPART <<< $(ogGetEsp)
EFIDEVICE=$(ogDiskToDev $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_NOTFOUND "ESP" || return $?
EFIMNT=$(ogMount $EFIDISK $EFIPART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR mount ESP" || return $?
EFIDIR="$EFIMNT/EFI"
[ -d $EFIDIR ] || mkdir $EFIDIR
# Comprobamos que exista shimx64
SHIM=$(ogGetPath /usr/lib/shim/shimx64.efi.signed)
[ "$SHIM" == "" ] && return $(ogRaiseError $OG_ERR_NOTFOUND "shimx64.efi.signed")
# Si existe configuración anterior de refind la borro
[ -d "$EFIDIR/refind" ] && rm -rf $EFIDIR/refind
# Instalamos rEFInd.
refind-install --yes --alldrivers --root $EFIMNT --shim $SHIM
# Firmo refind con certificado de OpenGnsys
mv $EFIDIR/refind/grubx64.efi $EFIDIR/refind/grubx64.efi-unsigned
sbsign --key $OGETC/ssl/private/opengnsys.key --cert $OGETC/ssl/certs/opengnsys.crt --output $EFIDIR/refind/grubx64.efi $EFIDIR/refind/grubx64.efi-unsigned
# Copio los certificados
cp /etc/refind.d/keys/* $EFIDIR/refind/keys
# Copio certificado opengnsys
cp $OGETC/ssl/certs/opengnsys.* $EFIDIR/refind/keys
# Ponemos la entrada en NVRAM en el segundo lugar del orden de arranque
NEWORDER="$(ogNvramGetOrder|awk '{gsub(",", " "); printf "%x %x %s\n", $2, $1, substr($0, index($0,$3))}')"
ogNvramSetOrder $NEWORDER
# Borramos configuración linux
[ -f $EFIMNT/boot/refind_linux.conf ] && mv $EFIMNT/boot/refind_linux.conf{,.ogbackup}
# Eliminamos punto de motaje (por si ejecutamos más de una vez)
umount $EFIMNT/boot/efi
# Para la configuración del ogLive
ogMountCache &>/dev/null
if [ $? -eq 0 ]; then
# Detectamos si hay ogLive
CACHEDEVICE=$(ogDiskToDev $(ogFindCache))
OGLIVE=$(find $OGCAC/boot -name ogvmlinuz|head -1)
# Obtenemos parametros del kernel y sustituimos root
# La línea de opciones no puede contener la cadena initrd.
CMDLINE="$(cat /proc/cmdline|sed -e 's/^.*ogvmlinuz.efi //g' -e 's/^.*ogvmlinuz //g' -e 's|root=/dev/[a-z]* ||g' \
-e 's/ogupdateinitrd=[a-z]* //g')"
CMDLINE="root=$CACHEDEVICE ${CMDLINE#*ogvmlinuz}"
# Icono para la entrada de menú
OGICON=$(ls $OGLIB/refind/icons/so_opengnsys.png 2>/dev/null)
[ "$OGICON" == "" ] && OGICON="${EFIDIR}/refind/icons/os_unknown.png"
cp "$OGICON" "$OGCAC/.VolumeIcon.png"
fi
# Configuramos rEFInd si es necesario
CFGFILE="${EFIDIR}/refind/refind.conf"
if [ "$CONFIG" == "TRUE" ]; then
echo -e "\n\n# Configuración OpenGnsys" >> $CFGFILE
# Excluimos dispositivos distintos de ESP y CACHE
DEVICES=$(blkid -s PARTUUID |awk -v D=$EFIDEVICE -v C=$CACHEDEVICE '$1!=D":" && $1!=C":" {gsub(/PARTUUID=/,"");gsub(/"/,""); aux = aux" "$2","} END {print aux}')
echo "dont_scan_volumes $DEVICES" >> $CFGFILE
# Excluimos en la ESP los directorios de los sistemas operativos
echo "dont_scan_dirs EFI/microsoft,EFI/ubuntu,EFI/grub" >> $CFGFILE
echo "use_graphics_for osx,linux,windows" >> $CFGFILE
echo "showtools reboot, shutdown" >> $CFGFILE
# Configuramos ogLive
if [ "$OGLIVE" != "" ]; then
# Cambiamos nombre de kernel e initrd para que lo detecte refind
OGLIVEDIR="$(dirname $OGLIVE)"
cp "$OGLIVE" "${OGLIVE}.efi"
cp "$OGLIVEDIR/oginitrd.img" "$OGLIVEDIR/initrd.img"
# Incluimos el directorio de ogLive.
echo "also_scan_dirs +,boot/$(basename $OGLIVEDIR)" >> $CFGFILE
# Fichero de configuración de refind para kernel de linux.
LNXCFGFILE="$OGLIVEDIR/refind_linux.conf"
echo "\"OpenGnsys Live\" \"$CMDLINE\"" > $LNXCFGFILE
# Ponemos ogLive como la entrada por defecto
NUMENTRY=$(ls -d $EFIDIR/Part-??-??|wc -l)
echo "default_selection $((NUMENTRY+1))" >> $CFGFILE
fi
else
# Renombramos la configuración por defecto
mv $CFGFILE ${CFGFILE}.auto
# Creamos nueva configuración
echo "# Configuración OpenGnsys" >> $CFGFILE
echo "timeout 20" > $CFGFILE
echo "showtools reboot, shutdown" >> $CFGFILE
echo -e "scanfor manual\n" >> $CFGFILE
# Configuración para sistemas restaurados con OpenGnsys
for DIR in $(ls -d /mnt/sda1/EFI/Part-*-* 2>/dev/null); do
echo "menuentry \"${DIR##*/}\" {" >> $CFGFILE
echo " loader /EFI/${DIR##*/}/Boot/ogloader.efi" >> $CFGFILE
[ -f $DIR/Boot/bootmgfw.efi ] && echo " icon /EFI/refind/icons/os_win8.png" >> $CFGFILE
[ -f $DIR/Boot/grubx64.efi ] && echo " icon /EFI/refind/icons/os_linux.png" >> $CFGFILE
echo "}" >> $CFGFILE
done
# Configuración ogLive si secureboot no está activado
if ! dmesg|grep secureboot.*enabled &>/dev/null; then
if [ "$OGLIVE" != "" ]; then
echo "menuentry \"OpenGnsys Live\" {" >> $CFGFILE
echo " volume CACHE" >> $CFGFILE
echo " ostype Linux" >> $CFGFILE
echo " loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE
echo " initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE
echo " options \"$CMDLINE\"" >> $CFGFILE
echo "}" >> $CFGFILE
# Ponemos ogLive como la entrada por defecto
sed -i '1 i\default_selection "OpenGnsys Live"' $CFGFILE
fi
fi
fi
}
#/**
# ogGrub4dosInstallMbr int_ndisk
#@brief Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
#@param int_ndisk nº de orden del disco
#@param int_ndisk nº de orden del particion
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
#@exception OG_ERR_NOTBIOS Equipo no firmware BIOS legacy
#@exception OG_ERR_NOMSDOS Disco duro no particioniado en modo msdos
#@exception OG_ERR_NOTWRITE Particion no modificable.
#@version 1.1.1 - Adaptacion a OpenGnSys.
#@author Alberto García Padilla / Antonio J. Doblas Viso. Universidad de Malaga
#@date 2009-10-17
#*/ ##
function ogGrub4dosInstallMbr ()
{
# Variables locales.
local DISK PART DEVICE MOUNTDISK GRUBDISK BINBDIR
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_part " \
"$FUNCNAME 1 1 "
return
fi
# Error si no se recibe 2 parámetros.
[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
DISK="$1"
PART="$2"
#Controlar existencia de disco y particion
DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $?
MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $?
#Controlar acceso de escritura a la particion
ogIsReadonly $DISK $PART && return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?)
#Controlar disco no uefi
ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?)
#Controlar particionado tipo msdos
ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?)
#Controlar la existencia del grub4dos con acceso a ntfs
BINDIR="${OGLIB}/grub4dos/grub4dos-0.4.6a"
[ -f ${BINDIR}/bootlace.com ] || ogRaiseError $OG_ERR_NOTFOUND ": ${BINDIR}/bootlace.com" || return $?
#instalar el bootloader de grlrd en el MBR
${BINDIR}/bootlace64.com $DEVICE &>/dev/null
#copiar grld a la particion
cp ${BINDIR}/grldr $MOUNTDISK
#Instalar y configurar grub4dos
if [[ -f $MOUNTDISK/boot/grub/menu.lst ]]; then
rm $MOUNTDISK/boot/grub/menu.lst
rmdir /$MOUNTDISK/boot/grub
fi
if [[ ! -f $MOUNTDISK/boot/grub/menu.lst ]]; then
mkdir -p /$MOUNTDISK/boot/grub
touch /$MOUNTDISK/boot/grub/menu.lst
GRUBDISK=$[$1-1]
cat << EOT >/$MOUNTDISK/boot/grub/menu.lst
##NO-TOCAR-ESTA-LINEA MBR
timeout 0
title MBR
root (hd$GRUBDISK,0)
chainloader (hd$GRUBDISK,0)+1
boot
EOT
fi
}