#!/bin/sh

# Copyright (c) 2024, Emrion

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.

# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


#### Functions & data ####

readonly Version="loaders-update v1.5.1"
# Available modes
readonly WMN="shoot-me"
readonly SMN="show-me"
readonly IMN="make-efi-failsafe"
# Loaders file names
readonly EFILOADER="loader.efi"
readonly EFILOADER32="loader_ia32.efi"
readonly FILEPREFIX="LU-"
readonly SAVEDEFILOADER="${FILEPREFIX}old-loader.efi"
readonly FAILSAFELABEL="${FILEPREFIX}FailSafe"
readonly PMBR="pmbr"
readonly GPTBOOT="gptboot"
readonly GPTZFSBOOT="gptzfsboot"
readonly EVLP="\-LoaderPath" # Name of the efi var for booted file
readonly EBO="\-BootOrder"
readonly TMPFILE="/tmp/${FILEPREFIX}data"

EMD="/mnt" # Mount point for efi partitions
SLD="/boot" # Loaders source dir
SBD="/root" # Place where the BIOS loaders are saved
# If the root file system must be checked or not (BIOS loaders update)
USE_RFS=true
# If the content of the freebsd-boot partition(s) must be checked or not
USE_FBP=true
# We prefer to use sysctl kern.disk to list the disks
USE_KERNDISK=true
Quiet=false		# No output if true
AutoYes=false	# Automatic Yes in shoot-me mode
OnlyEFI=false	# Scan only EFI loaders
OnlyBIOS=false	# Scan only BIOS loaders
BIOSbackup=true # The BIOS loaders will be saved before change
L32once=false
L64once=false
EfiSaved=false


Usage()
{
	echo "$Version"
	echo "Usage: $exn mode [-befgnoqry] [-m efi_mount_dir] [-s loaders_source_dir]"
	echo "mode can be one of:"
	echo "  $SMN: just show the commands to type, change nothing."
	echo "  $WMN: may update the loader(s), but ask for confirmation before each one."
	echo "  $IMN: set the EFI fail safe feature."
	echo "Options:"
	echo "  -b: scan only BIOS loaders (excludes EFI loaders)."
	echo "  -e: scan only EFI loaders (excludes BIOS loaders)."
	echo "  -f: won't check the freebsd-boot content for BIOS loaders update."
	echo "  -g: force to use 'gpart show' for disk detection."
	echo "  -n: don't backup the BIOS loaders."
	echo "  -o: specify the directory where to save the BIOS loaders. Default=$SBD"
	echo "  -q: quiet mode. No output to the console."
	echo "  -r: won't check the root file system for BIOS loaders update."
	echo "  -y: answer yes for $WMN mode. Use with caution!"
	echo "Return codes:"	
	echo "  0: no error."
	echo "  1: an error occured."
	echo "  2: at least one loader isn't up-to-date."
	echo "  3: = 1 + 2."
	exit 1
}

Report()
{
	if ($Quiet); then
		return
	fi
	echo $2 "$1"
}

TestRoot()
{
	if [ "$(id -u)" -ne 0 ]; then 
		Report "Consider to run this utility as root."
	fi
}

Ask()
{
	local rep
	read -p "$1 " rep
	case "$rep" in
		[yY]*) 	return 0;;
		*) return 1;;
	esac
}

# TestCmd cmd
# Warning: the command is executed, not only tested
TestCmd()
{
	local r
	r="$(eval "$1" 2>&1)"
	if [ $? -ne 0 ]; then
		echo "$r"
	fi
}

# PossiblyRun CmdToExecute VarUpdatable VarUpdated
PossiblyRun()
{
	local cmd rep
	local VarUpdatable	# Counts what it can be updated
	local VarUpdated	# Counts what it has been updated

	cmd="$1"
	VarUpdatable="$2"
	VarUpdated="$3"

	if ($SM); then	# SM is true if shoot-me Mode is selected
		unset rep
		if ! ($AutoYes); then
			echo "About to execute: $cmd"
			if ! Ask "Are you sure (y/N)?"; then
				echo "Nothing has been writted."
			   	eval "$VarUpdatable=\$(($VarUpdatable+1))"
	   	  	   	return
			fi
		fi 
		if ($Quiet); then
			eval "$cmd" > /dev/null
		else
			eval "$cmd"
		fi	
		if [ $? -eq 0 ]; then
			eval "$VarUpdated=\$(($VarUpdated+1))"
		else
			eval "$VarUpdatable=\$(($VarUpdatable+1))"
			Err=$((Err+1))
		fi
	else
		Report "Would run: $cmd"
		eval "$VarUpdatable=\$(($VarUpdatable+1))"
	fi 
}

# CheckSourceFile SourceFile
CheckSourceFile()
{
	if ! [ -e "$1" ]; then
		Report "Cannot find $1 on your system! Exiting."
		exit 1
	fi
}

# CopyEfiLoader TargetFile
CopyEfiLoader()
{
	local SourceFile TargetFile TFmd5 tfr Smd5
	# global FBSDL: is a loader found in TargetPartition?
	TargetFile="$1"

	# Checks if it's an executable efi file

	tfr="$(file -b "$TargetFile")"
	if [ -z "$(echo "$tfr" | grep PE32+)" ]; then
		return
	fi
	# Checks if the file is a FreeBSD loader
	if [ "$(grep -c FreeBSD "$TargetFile")" -gt 0 ]; then
		if uefisign -V "$TargetFile" 1>/dev/null 2>&1; then
			Report "Loader $TargetFile is signed (secure boot). Skiped."
			return
		fi
		FBSDL=true			
		TFmd5="$(md5 -q "$TargetFile")"
		# Determine if it is a 32 or a 64 bits loader
		if [ -z "$(echo "$tfr"|grep 386)" ]; then
			L64once=true
			Smd5="$Efimd5"
			SourceFile="$SLD/$EFILOADER"
		else
			L32once=true
			if [ "$Efi32md5" = "0" ]; then
				Report
				Report "Cannot update the 32 bits EFI loader:"
				Report "$TargetFile"
				Report "$SLD/$EFILOADER32 is absent."
				Ferr=$((Ferr+1))
				return
			fi
			Smd5="$Efi32md5"
			SourceFile="$SLD/$EFILOADER32"	
		fi
		if  [ "$TFmd5" = "$Smd5" ]; then
			Report "EFI loader $TargetFile is up-to-date."
		else
			# Save this loader in case we need it for SAVEDEFILOADER
			if ($SM); then 
				cp "$TargetFile" "$TMPFILE"
			fi	
			PossiblyRun "cp $SourceFile $TargetFile" UpEFI mEFI
		fi
	fi
}

# EfiUpdate TargetPartition MountedDest
EfiUpdate()
{
	local SourceFile TargetPartition MountedDest
	local mt cmd e lf f ptol
	# global FBSDL: is a loader found in TargetPartition?

	TargetPartition="$1"
	MountedDest="$2"
	mt=false

	# If $MountedDest is empty, the target partition isn't mounted, we must mount it
	if [ -z "$MountedDest" ]; then
		MountedDest="$EMD"
		cmd="mount -t msdosfs /dev/$TargetPartition $MountedDest"
		Report "$cmd"
		e="$(TestCmd "$cmd")"
		if [ -n "$e" ]; then
			Report "$e"
			Report "Cannot mount $TargetPartition, so cannot looking for its loader(s)."
			case "$e" in
				*Invalid*) Report "Is this partition formatted?"
					   Ferr=$((Ferr+1));;
				*) Err=$((Err+1));;
			esac
			return
		fi
		mt=true	# Don't forget to umount before returning
	fi

	FBSDL=false
	Imefi=$mEFI
	lf="$(find "$MountedDest" -type f -iname "*.efi")"
	for f in $lf; do
		# Test all .efi files except the saved efiloader.
		if [ -z "$(echo "$f" | grep "/$SAVEDEFILOADER")" ]; then
			CopyEfiLoader "$f"
		else
			ptol="$f"
		fi
	done
	if ! ("$FBSDL"); then
		Report "There is no FreeBSD loader in $TargetPartition"
	fi
	if [ -n "$ptol" ]; then
		# If an efi loader has been updated and the SAVEDEFILOADER is present
		# Copy the previous saved loader to old loader.
		if [ $mEFI -gt $Imefi ] && ! ($EfiSaved); then
			EfiSaved=true
			if ($L32once && $L64once); then
				Report "64 & 32 bits mix EFI loaders: cannot save the old loader."
				Ferr=$((Ferr+1))
			else
				Report "Saving old EFI loader in $ptol."
				cp "$TMPFILE" "$ptol"
			fi
		fi
	fi

	rm -f "$TMPFILE"
	if ($mt); then
		cmd="umount $MountedDest"
		Report "$cmd"
		if ($Quiet); then
			eval "$cmd" > /dev/null
		else
			eval "$cmd"
		fi
	fi	
}

# SelectBiosLoader (ufs or zfs)
SelectBiosLoader()
{
	# global BiosLoader BCmd5 LBC	# Path/name, MD5 and size of the selected source loader
	
	if [ "$1" = "zfs" ]; then
		BiosLoader="$Szfs"
		BCmd5="$ZfsMD5"
		LBC="$Lzfs"
	else
		BiosLoader="$Sgpt"
		BCmd5="$GptMD5"
		LBC="$Lgpt"
	fi
}

BiosUpdate()
{
	local Spmbr PmbrMD5				# Path/name & md5 of source pmbr
	# global Szfs ZfsMD5 Lzfs		# Path/name, md5 and size of source gptzfsboot
	# global Sgpt GptMD5 Lgpt		# Path/name, md5 and size of source gptboot
	# global BiosLoader BCmd5 LBC	# Path/name, MD5 and size of the selected source loader
	local d index p					# Disk, index and partition currenlty examined
	local rBTX rZFS rzfs			# Results / offset of strings search
	local eof 						# End of file offset in the freebsd-boot partition
	local pfs						# File system managed by the loader inside the partition
	# global rfs					# Root file system
	local CpmbrMD5 CfbbMD5			# MD5 of the current disk pmbr & partition content
	local bcode pcode i

	# Check the source pmbr 
	Spmbr="$SLD/$PMBR" # Path/name of the source loader
	CheckSourceFile "$Spmbr"
	PmbrMD5="$(head -c 446 "$Spmbr" | md5 -q)" # MD5 computation
	# Check the sources BIOS loaders gptzfsboot & gptboot
	Szfs="$SLD/$GPTZFSBOOT"
	CheckSourceFile "$Szfs"
	ZfsMD5="$(md5 -q "$Szfs")"
	Lzfs="$(stat -f "%z" "$Szfs")" # Size in bytes of the file
	Sgpt="$SLD/$GPTBOOT"
	CheckSourceFile "$Sgpt"
	GptMD5="$(md5 -q "$Sgpt")"
	Lgpt="$(stat -f "%z" "$Sgpt")"
	
	Report
	i=1
	for d in $BIOSD; do
		Report "Examining $d..."
		
		# Retrieving the corresponding partition index in BIOSI
		index=$(eval "echo \$BIOSI | awk '{ print \$$i }'")
		i=$((i+1))
		p="/dev/${d}p$index"

		# Is there a BTX loader in this partition?
		rBTX="$(grep -c 'BTX halted' "$p")"
		# Check first if the partition is readable
		if [ $? -gt 1 ]; then
			Report "Error during access to $p. Won't update these loaders."
			Err=$((Err+1))
			continue
		fi

		if ("$USE_FBP"); then
			if [ "$rBTX" -eq 0 ]; then
				Report "There is currently no loader in $p."
				Report "Cannot update without option -f."
				Ferr=$((Ferr+1))
				continue
			else
				# Try to determine whether the partition content is gptboot or gptzfsboot
				# $rZFS is set at the offset where the first string 'ZFS' has been detected
				rZFS="$(grep -abo ZFS "$p" | head -n1 | cut -f1 -d ':')"
				rzfs="$(grep -c zfs "$p")" # Detection of the string 'zfs'
				# $eof is near the end of the last file copied into this partition (sequence of 24 NUL bytes)
				eof=$(cat "$p" | hexdump -v -e '/1 "%02x"' | grep -bo -E '0{48}' | head -n1 | cut -f1 -d ':')
				if [ -z "$eof" ]; then
					Report "Cannot find eof in $p. It won't be analyzed."
					Report "Use option -f if you want to update it."
					Ferr=$((Ferr+1))
					continue
				fi
				eof=$((eof/2)) # Each byte is 2 characters in hexadecimal

				# The comparison of $rZFS versus $eof allows to detect a special case
				# where a partition has been filled with gptzfsboot, then filled with gptboot
				# in a second time. As the size of gptboot is << to the one of gptzfsboot,
				# the strings 'ZFS' and 'zfs' remain in the partition and would be falsely detected
				# as gptzfsboot otherwise.
				if [ -n "$rZFS" ] && [ "$rzfs" -gt 0 ] && [ "$rZFS" -lt "$eof" ]; then
					pfs="zfs" # gptzfsboot	
				else	
					pfs="ufs" # gptboot	
				fi
				SelectBiosLoader "$pfs"
			fi
		fi
		if ($USE_RFS) && ($USE_FBP) && ! [ "$rfs" = "$pfs" ]; then
			Report "There is a mismatch between the root fs and the current loader."
			Report "Root fs: $rfs / Partition has: $pfs."
			Report "--> No loader update on $p."
			Ferr=$((Ferr+1))
			continue
		fi
		if ! ($USE_FBP) && ($USE_RFS); then
			SelectBiosLoader "$rfs"
		fi	
		CpmbrMD5="$(head -c 446 /dev/"$d" | md5 -q)" # MD5 of current disk pmbr
		bcode="-b $Spmbr "
		if [ "$CpmbrMD5" = "$PmbrMD5" ]; then
			Report "The pmbr on this disk is up-to-date."
			unset bcode
		fi
		# MD5 of current freebsd-boot partition content
		CfbbMD5="$(head -c "$LBC" /dev/"${d}"p"$index" | md5 -q)" 
		pcode="-p $BiosLoader -i $index "
		if ! ("$USE_RFS"); then
			Report "Loader in ${d}p$index is $(basename "$BiosLoader")."
		fi
		if [ "$CfbbMD5" = "$BCmd5" ]; then
			Report "The freebsd-boot partition ${d}p$index is up-to-date."
			unset pcode
		fi
		if [ -n "$bcode" ] || [ -n "$pcode" ]; then
			Imbios=$mBIOS
			if ($SM) && ($BIOSbackup); then
				dd if="/dev/$d" bs=512 count=1 status=none > "$TMPFILE"
				dd if="/dev/${d}p$index" status=none > "${TMPFILE}1"
			fi		
			PossiblyRun "gpart bootcode $bcode$pcode$d" UpBIOS mBIOS
			if  ($BIOSbackup) && [ $mBIOS -gt $Imbios ]; then
				if [ -n "$bcode" ]; then
					cp "$TMPFILE" "$SBD/$PMBR.$d"
					Report "Previous $PMBR saved in $SBD/$PMBR.$d"
				fi
				if [ -n "$pcode" ]; then
					bln="$(basename "$BiosLoader")"
					cp "${TMPFILE}1" "$SBD/$bln.${d}p$index"
					Report "Previous $bln saved in $SBD/$bln.${d}p$index"
				fi
			fi
			rm -f "$TMPFILE" "${TMPFILE}1"	
		fi
	done
}

GetBootMethod()
{
	if [ -z "$BM" ]; then
		BM=$(sysctl -n machdep.bootmethod)
		if [ $? -ne 0 ]; then
			Report "Cannot get the boot method."	
		fi
	fi
}

GetEfiBootDevice()
{
	local cb=""
	local lp
	if [ -z "$eebm" ]; then
		cb="$(efibootmgr -v | grep +)"
		if [ -n "$cb" ]; then
			# It may be impossible for efibootmgr to convert to a unix path
			efibootmgr -E > /dev/null 2>&1
			if [ $? -gt 0 ]; then
				# Just print the line reported by efibootmgr
				cb="$(echo "$cb@" | cut -f3- -d ' ')"
			else
				# There, we can identify the boot partition
				cb="$(efibootmgr -E)"
				# Case where the boot partition is a label, convert it to a geom partition
				if [ -n "$(echo "$cb" | grep gpt/)" ]; then
					lp="$(echo "$cb" | cut -f2 -d /)"
					if [ -n "$lp" ] && [ -z "$egs" ]; then	
						cb="$(gpart show -lp | grep "$lp" | awk '{ print $3 }')" 
						
					fi
				fi
				cb="$(echo "$cb"|sed -e 's#\\#/#g')"     # Change \ for /
				cb="$(echo "$cb" | sed -e 's#/dev/##1')" # Remove "/dev/"
			fi
		fi
	fi
	echo "$cb"
}

GetEfiLoaderPath()
{
	local lpf="$(TestCmd efivar)"
	if [ -z "$lpf" ]; then
		lpf="$(efivar -l | grep "$EVLP")" # Get the real var name with uuid
		if [ -n "$lpf" ]; then
			lpf="$(efivar "$lpf" -N --utf8)"
			lpf="$(echo "$lpf"|sed -e 's#\\#/#g')"
		fi
	else
		unset lpf	
	fi
	echo "$lpf"	
}

GetEfiMount() # Check if partition $1 is already mounted
{
	local p="$1"
	local m=""
	# Try to see if the efi partition is already mounted
	# Search first by the geom name (e.g. ada0p1)
 	m="$(mount -p | grep "$p\s" | awk '{ print $2 }')"
	# If not found, try by the label name (e.g. efiboot0)
	if [ -z "$m" ]; then
		if [ -n "$egs" ]; then
			Report "$egs"
			Err=$((Err+1))
	fi 
 	lp="$(gpart show -pl | grep "$p\s" | awk '{ print $4 }')"
	m="$(mount -p | grep "$lp\s" | awk '{ print $2 }')"
	fi
	# If not found, look for geom name symlinks
	if [ -z "$m" ]; then 
    		lf="$(find "/dev" -type l)"
    		for f in $lf; do
        		if [ "$(readlink "$f")" = "$p" ]; then
				m="$(mount -p | grep "$(basename "$f")\s" | awk '{ print $2 }')"
				if [ -n "$m" ]; then
            				break
        			fi
			fi
    		done
	fi
	echo "$m"
}

#### Main ####

# To avoid some errors related to grep
unset GREP_OPTIONS

exn=$(basename "$0")
Mode="$1"
IM=false
SM=false
case "$Mode" in
	"$WMN") SM=true;;
	"$SMN") SM=false;;
	"$IMN") IM=true;;
	*) Usage;;
esac 

shift
while getopts "m:s:o:rgfebnqy" opt; do
	case ${opt} in
		m) EMD="${OPTARG}";;
		s) SLD="${OPTARG}";;
		o) SBD="${OPTARG}";;
		n) BIOSbackup=false;;
		r) USE_RFS=false;;
		g) USE_KERNDISK=false;;
		f) USE_FBP=false;;
		e) OnlyEFI=true;;
		b) OnlyBIOS=true;;
		q) Quiet=true;;
		y) AutoYes=true;;
		*) Usage;;
	esac
done

Report "$Version"

if ($IM); then
	OnlyEFI=true;
	OnlyBIOS=false;
fi

if [ "$(id -u)" -ne 0 ] && (($SM) || ($IM)); then 
	Report "You need to be root to operate in $Mode mode."
	return 1
fi

# In case someone has the idea to rise both options
if ($OnlyEFI) && ($OnlyBIOS); then
	Report "Options -b and -e are mutually exclusive. Exiting."
	return 1
fi
if ! ($USE_RFS) && ! ($USE_FBP); then
	Report "Options -r and -f are mutually exclusive. Exiting."
	return 1
fi
if ! [ -d "$EMD" ] && ! ($OnlyBIOS); then
	Report "EFI mount point doesn't exist: $EMD"
	return 1
fi
if ! ($IM) && ! [ -d "$SLD" ]; then
	Report "Loaders source dir doesn't exist: $SLD"
	return 1
fi

if ($SM) && ! ($OnlyEFI) && ! [ -d "$SBD" ]; then
	Report "BIOS backup dir doesn't exist: $SBD"
	return 1
fi

arch="$(sysctl -n hw.machine)"
if [ $? -ne 0 ]; then
	Report "Cannot get the architecture. Exiting."
	Report
	return 1
fi
case "$arch" in
	arm64)
			OnlyEFI=true # No Bios loader for arm64
			OnlyBIOS=false
			BM="UEFI"
			USE_KERNDISK=false # gpart is better to see disks for these machines
			;;
	amd64)
			;; # Nothing to do
	*)
			Report "This utility works only with amd64 or arm64 architectures. Exiting."
			Report
			return 1
			;;
esac

# Check some cmd to detect a problem with hardened systems
em=$(TestCmd "mount -p")
egs=$(TestCmd "gpart show")
if [ "$(id -u)" -eq 0 ]; then
	eebm="$(TestCmd efibootmgr)"
fi

# Get the list of disks
if ($USE_KERNDISK); then 
	LD="$(sysctl -n kern.disks)"
	if [ $? -ne 0 ]; then
		Report "Cannot get the list of disks."
		Report "'sysctl kern.disks' doesn't work. Exiting."
		Report
		return 1
	fi
else
	if [ -z "$egs" ]; then
		LD="$(gpart show | grep GPT | cut -wf4)"
	else
		Report "Cannot get the list of disks."
		Report "'gpart show' doesn't work. Exiting."
		Report "$egs"
		Report
		return 1
	fi
fi
if [ -z "$LD" ]; then
	if ! ($USE_KERNDISK); then
		Report "No GPT disk has been detected. Exiting."
	else
		Report "No disk has been detected. Exiting."
	fi
	Report
	return 1
fi

if ! ($SM) && ($AutoYes); then
	Report "Option -y has no sense in $Mode mode."
fi
Report

# Search for efi & freebsd-boot partitions
GPT=false
for d in $LD; do
	# To avoid an error if the disk is amovible and absent (cdrom)
	gpart show "$d" > /dev/null 2>&1

	if [ $? -eq 0 ]; then
		gp="$(gpart show "$d" | head -n1 | awk '{ print $5 }')"
		if [ "$gp" = "GPT" ]; then
			GPT=true
			# Looking for a efi type partition
			if ! ($OnlyBIOS); then
				p="$(gpart show -p "$d" | grep efi | awk '{ print $3 }')"
				if [ -n "$p" ]; then
					EFIP="$EFIP $p"
				fi
			fi
			# Looking for a freebsd-boot type partition
			if ! ($OnlyEFI); then
				pi="$(gpart show "$d" | grep freebsd-boot | awk '{ print $3 }')"
				if [ -n "$pi" ]; then
					# BIOSD lists the disks and BIOSI the corresponding indexes
					BIOSD="$BIOSD $d"
					BIOSI="$BIOSI $pi"
				fi
			fi	
		fi
	fi
done

if ! ($GPT); then
	Report "This machine seems to have no disk with GPT scheme. Exiting."
	Report
	return 1
fi

#---------------------------------------------------------
# Try here to activate the EFI fail safe feature, if asked.
#---------------------------------------------------------
if ($IM); then 
	GetBootMethod
	if ! [ "$BM" = "UEFI" ]; then
		Report "$Mode works only with UEFI boot method."
		return 1
	fi
	if [ -z "$EFIP" ]; then
		Report "No EFI partition have been found. Cannot go further."
		return 1
	fi
	if [ -z "$eebm" ]; then
		if [ -n "$(efibootmgr -v|grep $FAILSAFELABEL)" ]; then
			Report "EFI fail safe feature is already enabled."
			return 1
		fi
	else
		Report "efibootmgr doesn't work:"
		Report "-> $eebm"
		return 1
	fi	
	ebd="$(GetEfiBootDevice)"
	if [ -z "$ebd" ]; then
		Report "Cannot get the EFI boot device."
		return 1
	fi
	if [ -n "$(echo "$ebd"|grep @)" ]; then
		cnfbd=true
	else
		cnfbd=false
	fi

	echo "About to implant loaders-update EFI fail safe feature in your machine."
	echo "Warning: if you have a bogus EFI firmware, this may fail without notice."
	if  ! Ask "Are you ok with that (y/n)?"; then
		return 1
	fi	
	if ($cnfbd); then # Here, efibootmgr didn't success to convert to a UNIX path
		# Look into found efi partitions, if there is only one, it's this one.
		if [ "$(echo "$EFIP"| wc -w)" -eq 1 ]; then
			ebd="$(echo "$EFIP"| sed -e 's# ##1')"
		else # Several possibilities, ask to the admin
			echo "Choose the partition where to install:"
			echo "$EFIP"
			while true; do
				read -p "Which one? " rep
				if [ -n "$rep" ]; then
					case $EFIP in
						*" $rep"*) break;;
					esac
				fi
				echo "Please choose a detected partition..."
			done
			ebd="$rep"
		fi
	fi
	# Try to see if the partition is already mounted or not
	mnt=false
	m="$(GetEfiMount "$ebd")"
	if [ -z "$m" ]; then
		if ! mount -t msdosfs "/dev/$ebd" "$EMD"; then
			Report "Cannot mount the booting partition: $ebd."
			return 1
		else
			m="$EMD"
			mnt=true
		fi
	fi
	elp="$(GetEfiLoaderPath)"
	if [ -z "$elp" ]; then
		Report "Cannot get the actual EFI loader path."
		if ($mnt); then
			umount "$m"
		fi
		return 1
	fi
	fcp="$(dirname "$(readlink -f "$m/$elp")")"
	if  ! cp "$m/$elp" "$fcp/$SAVEDEFILOADER"; then
		Report "Cannot copy loader to $SAVEDEFILOADER."
		if ($mnt); then
			umount "$m"
		fi
		return 1
	fi
	if ! efibootmgr -ca -l "$fcp/$SAVEDEFILOADER" -L "$FAILSAFELABEL" > /dev/null; then
		Report "Cannot create the efi var."
		Report "Nevertheless, the loader will be saved in $SAVEDEFILOADER."
		if ($mnt); then
			umount "$m"
		fi
		return 1
	fi
	if ($mnt); then
		umount "$m"
	fi
	bo="$(efivar -l | grep "$EBO")" # Get the real var name with uuid
	if [ -z "$bo" ]; then
		Report "Cannot get the BootOrder EFI var."
		Report "Please correct the boot order with efibootmgr -o ..."
		return 1
	fi
	efivar "$bo" -Nb > "$TMPFILE"
	dd if="$TMPFILE" bs=1 skip=2 status=none of="${TMPFILE}1"
	dd if="$TMPFILE" bs=1 count=2 status=none >> "${TMPFILE}1"
	cat "${TMPFILE}1" | efivar "$bo" -w
	r=$?
	rm "$TMPFILE" "${TMPFILE}1"
	if [ $r -ne 0 ]; then
		Report "Cannot set the BootOrder EFI var."
		Report "Please correct the boot order with efibootmgr -o ..."
		return 1
	fi
	Report "loaders-update EFI fail safe feature implanted."
	Report "Check with efibootmgr -v before and after reboot that all is ok."
	return 0 
fi

#---------------------------------------------------------
# Operations in show-me or shoot-me modes
#---------------------------------------------------------	
Err=0      # Errors that may be resolved by running this script as root
Ferr=0     # Other errors
UpEFI=0    # Updatable EFI loaders
UpBIOS=0   # Updatable BIOS loaders
mEFI=0     # Updated EFI loaders
mBIOS=0    # Updated BIOS loaders

if ($OnlyEFI); then
	Report "Scaning only EFI loaders, excluding BIOS loaders."
fi
if ($OnlyBIOS); then
	Report "Scaning only BIOS loaders, excluding EFI loaders."
fi

if [ -n "$EFIP" ]; then
	Report "One or more efi partition(s) have been found."
	CheckSourceFile "$SLD/$EFILOADER"
	# The 32 bits EFI loaders don't exist on all FreeBSD versions
	if [ -e "$SLD/$EFILOADER32" ]; then
		Efi32md5="$(md5 -q "$SLD/$EFILOADER32")"
	else
		Efi32md5=0
	fi
	Efimd5="$(md5 -q "$SLD/$EFILOADER")"

	Report
	if [ -n "$em" ]; then
			Err=$((Err+1))
			Report "Cannot work on EFI loaders because 'mount -p' doesn't work."
			Report "-> $em"
	else
		# Check if uefisign is present
		if [ -z "$(which uefisign)" ]; then
			Report "Warning: cannot find uefisign executable."
			Report "If you have secure boot enabled, don't use $exn."
			Report
		fi
		for p in $EFIP; do
			Report "Examining $p..."
			m="$(GetEfiMount "$p")"
			if [ -n "$m" ]; then
				Report "Efi partition $p is already mounted in $m."
			fi	
			EfiUpdate "$p" "$m"
		done
	fi
	if [ -n "$ptol" ]; then
		Report "The Efi fail safe feature seems to be enabled."
	else
		Report "The Efi fail safe feature isn't enabled."
	fi
	if ($L32once && $L64once); then
		Report
		Report "WARNING: you have a mix of 64 and 32 bits EFI loaders."
		if [ -n "$ptol" ]; then
			Report "As a result, the Efi fail safe feature won't work."
		fi
	fi
Report
fi

if [ -n "$BIOSD" ]; then
	Report "One or more freebsd-boot partition(s) have been found."
	if ! ($USE_FBP); then
		Report "The content of the freebsd-boot partition(s) won't be analyzed."
	fi
	# Check the root file system
	if ($USE_RFS); then
		if [ -z "$em" ]; then
			rfs="$(mount -p | grep "\s/\s" | awk '{ print $3 }')"
			if [ -n "$rfs" ]; then
				Report "The root file system is $rfs."
				BiosUpdate
			else
				Report "Cannot determine the root file system."
				Report "Won't work on the freebsd-boot partition(s)."
				Err=$((Err+1))
			fi
		else
			Report "The root fs must be checked, but 'mount -p' doesn't work."
			Report "-> $em"
			Err=$((Err+1))
		fi
	else
		Report "The root file system won't be checked."
		BiosUpdate
	fi
Report
fi

RetCode=0
Report "-------------------------------"

GetBootMethod
if [ -n "$BM" ]; then
	Report "Your current boot method is $BM."
	
	# Try to figure out partition & efi file on which the system is currently booting
	if [ "$BM" = "UEFI" ] && [ "$(id -u)" -eq 0 ]; then
		ebd="$(GetEfiBootDevice)"
		ebd="$(echo "$ebd"|sed -e 's#@##1')"
		if [ -n "$ebd" ]; then
			Report "Boot device: $ebd"
		fi
		# Get the loader path
		lpf="$(GetEfiLoaderPath)"
		if [ -n "$lpf" ]; then
			Report "Loader path: $lpf"
		fi
	fi
else
	Report "Cannot get the boot method."
fi

if [ -z "$EFIP" ] && [ -z "$BIOSD" ]; then
	Report "Found no partition containing a loader."
	Report "Nothing seems updatable."
else
	if [ "$mEFI" -eq 0 ] && [ "$mBIOS" -eq 0 ] && [ "$UpEFI" -eq 0 ] && [ "$UpBIOS" -eq 0 ]; then
		Report "One or more target partition(s) have been found..."
		if [ "$Err" -gt 0 ]; then
			Report "But no loader seems to be updatable."
			Report "$Err error(s) occured during the scan."
			TestRoot
			RetCode=1
		else
			if [ "$Ferr" -eq 0 ]; then
				Report "All loaders are up-to-date."
			fi
		fi
	else
		if [ "$UpEFI" -gt 0 ]; then
			Report "Updatable EFI loader: $UpEFI"
			RetCode=2
		fi
		if [ "$UpBIOS" -gt 0 ]; then
			Report "Updatable BIOS loader: $UpBIOS"
			RetCode=2
		fi
		if [ "$mEFI" -gt 0 ]; then
			Report "Updated EFI loader: $mEFI"
		fi
		if [ "$mBIOS" -gt 0 ]; then
			Report "Updated BIOS loader: $mBIOS"
		fi
		if  [ "$Err" -gt 0 ]; then
			Report "One or more loaders may be updatable, but encountered $Err error(s)."
			TestRoot
			RetCode=3
		fi
	fi
	if [ "$Ferr" -gt 0 ]; then
		Report "$Ferr serious error(s) occured. See texts above."
		RetCode=$((RetCode+1))
		if [ $RetCode -gt 3 ]; then
			RetCode=3
		fi
	fi
fi
Report "-------------------------------"

return $RetCode

