#!/bin/bash

# SPDX-License-Identifier:  GPL-2.0+

# Installer rootfs for ALT Linux
# Current version
VERSION=0.3.0

. shell-error

# Variable
BBL=2E54B353-1271-4842-806F-E436D6AF6985
EXT4=0FC63DAF-8483-4772-8E79-3D69D8477DE4
TMPFIRM=
TMPROOT=
LOG="$TMP/alt-rootfs-installer.log"
PROGNAME="${0##*/}"
unset ROOTPART_UID
unset FIRMPART_UID

MB=1048576		# one Mebibyte = 2^20

# usage message
usage() {
	echo "
Usage: $PROGNAME <options>

	--rootfs=ROOTFS   - archive rootfs file name
	--image-in=IMAGE  - image file name (img|img.xz)
	--media=DEVICE    - media device file (/dev/[sdX|mmcblkX])
	--image-out=FILE  - out image file
	--image-size=SIZE - size out image file (MiB)
	--target=TARGET   - target board
	--supported       - List of supported hardware
	--version         - Display version and exit
	--log             - Log file (default $LOG)
	-y                - Assumes yes, will not wait for confirmation

Example: $PROGNAME --rootfs=regular-lxqt-20190213-aarch64.tar.xz --target=rpi3 --media=/dev/mmcblk0

Update U-Boot for another Target
Update to a new u-boot from a local host install.

Example: $PROGNAME --target=orangepi_prime --media=/dev/mmcblk0

"
}

pre_exit () {
	local rc=$?
	trap - EXIT
	sync
	if [ -n "$TMPFIRM" ] && [ -d "$TMPFIRM" ]; then
		umount "$TMPFIRM" >> "$LOG" 2>&1
		rmdir "$TMPFIRM" >> "$LOG" 2>&1
	fi
	if [ -n "$TMPROOT" ] && [ -d "$TMPROOT" ]; then
		umount "$TMPROOT" >> "$LOG" 2>&1
		rmdir "$TMPROOT" >> "$LOG" 2>&1
	fi
	if [ "$TARGET" = "jetson-nano" ]; then
		rm -fr "$TMP/Linux_for_Tegra"
	fi
	if [ -n "$IMAGE_OUT" -a -n "$MEDIA" ]; then
		kpartx -d -s "$MEDIA" || {
			sleep 10
			kpartx -d -s -v "$MEDIA"
		}
		losetup --detach "$MEDIA"
	fi
	exit $rc
}

final_exit () {
	echo ""
	echo "= Installation Complete!"
	if [ -n "$IMAGE_OUT" ]; then
		echo "= Image created successfully."
	else
		echo "= Insert into the "$TARGET" and boot."
	fi
	exit 0
}

wget_jetson_nano () {
	if [ "$NOASK" != 1 ]; then
		rm -fr "$JETSON_PATH/$JETSON_ARCHIVE"
		echo "*** $JETSON_ARCHIVE not downloaded"
		read -p "= Download? " DOWNLOAD
		case "$DOWNLOAD" in
			[Yy][Ee][Ss])
				;;
			*)
				fatal "Error: $JETSON_ARCHIVE not downloaded!!!"
				;;
		esac
	fi
	echo "*** Download https://developer.nvidia.com/embedded/$JETSON_ARCHIVE..."
	wget "https://developer.nvidia.com/embedded/dlc/$JETSON_ARCHIVE" \
	  -P "$JETSON_PATH"
	echo "*** Extract Jetson Nano driver archive..."
	tar -xf "$JETSON_PATH/$JETSON_ARCHIVE" -C "$TMP"
	if [ $? -ne 0 ]; then
		rm -fr "$JETSON_PATH/$JETSON_ARCHIVE"
		fatal "Error: bad archive. Removed $JETSON_ARCHIVE"
	fi
}

# Set some global variables for the command directory, target board directory,
# and valid targets.
DIR="$(pwd $0)"
if [ -d "${DIR}/boards.d" ]; then
	BOARDDIR="${DIR}/boards.d"
	DOC_DIR="${DIR}/"
else
	if [ -d "/usr/share/alt-rootfs-installer/boards.d" ]; then
		BOARDDIR="/usr/share/alt-rootfs-installer/boards.d"
		DOC_DIR="/usr/share/doc/alt-rootfs-installer/"
	else
		fatal "ERROR: directory boards.d not exist"
	fi
fi

# missing or wrongs arguments
[ $# -ge 1 ] &&
TMPARGS="$(getopt -n "$0" -o hy -l debug,help,target:,rootfs:,media:,\
image-in:,image-out:,image-size:,supported,version,log: -- "$@")"
if [ $? -ne 0 ]; then
	usage
	exit 1
fi

eval set -- "$TMPARGS"
# check the args
while :; do
	case $1 in
		--)
			shift; break
			;;
		--debug)
			set -x
			;;
		-h|--help)
			usage; exit 0
			;;
		--target)
			shift; TARGET="$1"
			;;
		--rootfs)
			shift; ROOTFS="$1"
			;;
		--image-in)
			shift; IMAGE="$1"
			;;
		--media)
			shift; MEDIA="$1"
			;;
		--image-out)
			shift; IMAGE_OUT="$1"
			;;
		--image-size)
			shift; IMAGE_SIZE="$1"
			;;
		--supported)
			cat "$DOC_DIR/SUPPORTED-BOARDS"
			exit 0
			;;
		--version)
			echo "$PROGNAME-$VERSION"
			exit 0
			;;
		--log)
			shift
			LOG="$(readlink -f "$1")"
			;;
		-y)
			NOASK=1
			;;
		*)
			message "Error - ${1}"
			usage
			exit 1
			;;
	esac
	shift
done

# getting full PATH
[ -n "$ROOTFS" ] \
&& ROOTFS=$(echo $(cd $(dirname "$ROOTFS") && pwd -P)/$(basename "$ROOTFS"))
[ -n "$IMAGE" ] \
&& IMAGE=$(echo $(cd $(dirname "$IMAGE") && pwd -P)/$(basename "$IMAGE"))
[ -n "$IMAGE_OUT" ] \
&& IMAGE_OUT=$(echo $(cd $(dirname "$IMAGE_OUT") && pwd -P)/$(basename "$IMAGE_OUT"))

# checking the entered value --image-size
if [ -n "$IMAGE_SIZE" ]; then
	case "$IMAGE_SIZE" in
		*[!0-9]*) fatal "Error: bad image size." ;;
	esac
fi

# ensure sudo user
if [ "$(whoami)" != "root" ]; then
	fatal "Error: This script requires 'sudo' privileges in order to write to disk & mount media."
fi

# cleanup log file
if [ ! -d "${LOG%/*}" ]; then
	fatal "Can't locate directory ${LOG%/*} for log file. Exit"
fi
> "$LOG"

if [ -n "$IMAGE_OUT" -a -n "$MEDIA" ]; then
	fatal "Error: At the same time, mutually exclusive options are indicated: --media and --image-out"
fi

if [ -n "$IMAGE" -a -n "$ROOTFS" ]; then
	fatal "Error: At the same time, mutually exclusive options are indicated: --image and --rootfs"
fi

if [ "$TARGET" = "jetson-nano" -a -z "$ROOTFS" ]; then
	fatal "Error: --target=jetson-nano requires option --rootfs="
fi

# check to make image file
if [ -n "$IMAGE_OUT" ]; then
	MEDIA="$(losetup --find)" || fatal "Error: /dev/loop* not allowed"
fi

# check to make sure populated
if [ "$MEDIA" = "" ]; then
	usage
	exit 1
fi

if [ -z "$TARGET" -a -z "$ROOTFS" -a -z "$IMAGE" ]; then
	usage
	exit 1
fi

if [ "$MEDIA" = "/dev/sda" ]; then
	echo ""
	echo " ***********************************************************"
	echo " ** WARNING: You have requested the rootfs be written to sda."
	echo " ** /dev/sda is usually the root filesystem of the host. "
	echo " ***********************************************************"
	echo " ** Do you wish to continue? (type 'yes' to continue)"
	echo " ***********************************************************"
	# wait for agreement
	read -p " = Continue? " AGREE
	case "$AGREE" in
		[Yy][Ee][Ss])
			;;
		*)
			echo "User exit, no rootfs written."
			exit 0
			;;
	esac
fi

# rootfs exists
if [ ! -f "$ROOTFS" ] && [ "$ROOTFS" != "" ]; then
	fatal "Error: $ROOTFS not found! Please choose an existing rootfs."
fi

# image exists
if [ ! -f "$IMAGE" ] && [ "$IMAGE" != "" ]; then
	fatal "Error: $IMAGE not found! Please choose an existing image."
fi

# check image format
if [ -n "$IMAGE" ]; then
	case "$IMAGE" in
		*.img)
			CAT='cat'
			;;
		*.img.xz)
			CAT='xzcat'
			;;
		*) fatal 'Error: unknown image format'
			;;
	esac
	# NOTE: We assume there is no arch names containing '-' or '.'
	ARCH="${IMAGE##*-}"
	ARCH="${ARCH%%.*}"
fi

# definition of the rootfs archive format and ARCH
if [ -n "$ROOTFS" ]; then
	case "$ROOTFS" in
		*.tar)
			TAR='tar -xf'
			let "TAR_SIZE = $(stat -Lc %s "$ROOTFS") / $MB"
			;;
		*.tar.gz)
			TAR='tar -zxf'
			let "TAR_SIZE = $(gzip --list "$ROOTFS" | awk 'END{print $2}') / $MB"
			;;
		*.tar.xz)
			TAR='tar -Jxf'
			let "TAR_SIZE = $(xz --robot --list "$ROOTFS" | awk '/^totals/{print $5}') / $MB"
			;;
		*) fatal 'Error: unknown rootfs archive format'
			;;
	esac
	if [ -n "$IMAGE_OUT" ]; then
		# Add 256 MiB to the image size for bios, firmware, bootloader, etc and increase size by 10%
		# which is reserved by FS, take into account i-node ratio and reserved 32Mb. Add 1 just in case.
		IMAGE_SIZE_MIN="$(awk -vTS="$TAR_SIZE" -vM="$MB" 'BEGIN{ printf ("%d", ((TS+256+32)*(1+256/8192)*1.1+1)) }')"
		# Change image size
		[ -z "${IMAGE_SIZE-}" ] || [ "$IMAGE_SIZE_MIN" -ge "$IMAGE_SIZE" ] \
		&& IMAGE_SIZE="$IMAGE_SIZE_MIN"
		let "END_SECTOR = $IMAGE_SIZE - 1"
		END_SECTOR="$END_SECTOR"MiB
	fi
	# NOTE: We assume there is no arch names containing '-' or '.'
	ARCH="${ROOTFS##*-}"
	ARCH="${ARCH%%.*}"
fi

# device exists
if [ ! -e "$MEDIA" ]; then
	fatal "Error: $MEDIA not found! Please choose an existing device."
fi

# change cubietruck target to uppercase
if [ "$TARGET" = "cubietruck" ]; then
	TARGET="Cubietruck"
fi

# check for boards
if [ "$TARGET" != "" -a ! -e "${BOARDDIR}/${TARGET}" ]; then
	message "Error: You must choose a supported board or none at all." 
	usage
	exit 1
fi

if [ "$TARGET" != "" -a -L "$BOARDDIR/$TARGET" ]; then
	SOCS="$(basename $(readlink -e "$BOARDDIR/$TARGET"))"
	SOCS_ARCH="${SOCS#*-}"
else
	SOCS="$TARGET"
	unset SOCS_ARCH
fi

# socs and ARCH compliance check
if [ "$SOCS_ARCH" != "" -a "$ARCH" != "" -a "$SOCS_ARCH" != "$ARCH" ]; then
	fatal "Error: You must choose a supported board or none at all."
fi

if [ "$TARGET" = "rpi3" ] && [ "$ARCH" = "armh" ]; then
	fatal "Error: This rootfs does not support Raspberry Pi 3"
fi
if [ "$TARGET" = "rpi2" ] && [ "$ARCH" = "aarch64" ]; then
	fatal 'Error: This rootfs does not support Raspberry Pi 2'
fi

# Last chance to back out
echo ""
echo "====================================================="
if [ -n "$IMAGE_OUT" ]; then
echo "= Image out:       $IMAGE_OUT"
echo "= Image size:      $IMAGE_SIZE MiB"
else
echo "= Selected Media:  $MEDIA"
fi
# target hardware ARCH
if [ -n "$TARGET" ]; then
echo "= Target:          $TARGET"
fi
# rootfs if included
if [ -n "$ROOTFS" ]; then
echo "= Selected rootfs: $ROOTFS"
fi
# image-in if included
if [ -n "$IMAGE" ]; then
echo "= Selected image:  $IMAGE"
fi
echo "= Log file:        $LOG"
echo "====================================================="
echo " "
if [ -z "$IMAGE_OUT" ]; then
echo "*****************************************************"
echo "*****************************************************"
if [ -n "$IMAGE" -o -n "$ROOTFS" ]; then
echo "******** WARNING! ALL DATA WILL BE DESTROYED ********"
else
echo "******* WARNING! BOOTLOADER WILL BE REWRITED ********"
fi
echo "*****************************************************"
echo "*****************************************************"
fi

if [ "$NOASK" != 1 ]; then
	echo " "
	echo " Type 'YES' to proceed, anything else to exit now "
	echo " "
	# wait for agreement
	read -p "= Proceed? " PROCEED
	case "$PROCEED" in
		[Yy][Ee][Ss])
			;;
		*)
			echo "User exit, no rootfs written."
			exit 0
			;;
	esac
fi

case "$MEDIA" in
	/dev/mmcblk*|/dev/loop*)
		partsuffix="p"
		;;
	*)
		unset partsuffix
		;;
esac

case "$SOCS" in
	jetson_nano-aarch64)
		BBLPART=
		BOOTFLAG=
		FIRMPART=
		MEDIATABLE=
		ROOTPART_NUM=1
		;;
	Rockchips-*)
		BBLPART=
		BOOTFLAG=legacy_boot
		FIRMPART=
		MEDIATABLE=gpt
		ROOTPART_NUM=1
		START_SECTOR=16MiB
		;;
	*-riscv64)
		BBLPART=1
		BOOTFLAG=
		FIRMPART=
		MEDIATABLE=gpt
		ROOTPART_NUM=2
		;;
	rpi2|rpi3)
		BBLPART=
		BOOTFLAG=boot
		FIRMPART="${MEDIA}${partsuffix}1"
		MEDIATABLE=msdos
		ROOTPART_NUM=2
		;;
	*)
		BBLPART=
		BOOTFLAG=
		FIRMPART=
		MEDIATABLE=msdos
		ROOTPART_NUM=1
		;;
esac

[ -n "$ROOTPART" ] || ROOTPART="${MEDIA}${partsuffix}${ROOTPART_NUM}"

trap pre_exit EXIT HUP PIPE INT QUIT TERM

# Prepare device
if [ -n "$IMAGE_OUT" -a -z "$IMAGE_TEGRA" ]; then
	echo "Create image $IMAGE_OUT..."
	dd if=/dev/zero of="$IMAGE_OUT" bs="$MB" count="$IMAGE_SIZE" \
	|| fatal "Error: Create image $IMAGE_OUT failed"
	losetup "$MEDIA" "$IMAGE_OUT"
else
# umount before starting
	umount "${MEDIA}${partsuffix}"?* >> "$LOG" 2>&1
fi

# Create Nvidia Jetson Nano image
if [ "$TARGET" = "jetson-nano" ]; then
	JETSON_ARCHIVE="l4t-jetson-driver-package-32-1-jetson-nano"
	JETSON_PATH="/root"
	JETSON_TMP="$TMP/Linux_for_Tegra"
	if [ -n "$IMAGE_OUT" ]; then
		IMAGE_TEGRA="$IMAGE_OUT"
		IMAGE_SIZE="$IMAGE_SIZE"MiB
	else
		IMAGE_TEGRA=sd.img
		IMAGE_SIZE=128MiB
	fi
	rm -fr "$JETSON_TMP"
	if [ -f "$JETSON_PATH/$JETSON_ARCHIVE" ]; then
		echo "Extract Jetson Nano driver archive..."
		tar -xf "$JETSON_PATH/$JETSON_ARCHIVE" -C "$TMP" \
		|| wget_jetson_nano
	else
		wget_jetson_nano
	fi
	echo "Create Jetson Nano image"
	cd "$JETSON_TMP" \
	&& sed -i 's/sudo//g' create-jetson-nano-sd-card-image.sh \
	&& yes |./create-jetson-nano-sd-card-image.sh -o "$IMAGE_TEGRA" \
	  -s "$IMAGE_SIZE" -r 100  >> "$LOG" 2>&1 \
	|| fatal "Error: create Jetson Nano image failed!!!"
	if [ -z "$IMAGE_OUT" ]; then
		echo "Write Jetson Nano image"
		dd if="$IMAGE_TEGRA" of="$MEDIA" bs=1M >> "$LOG" 2>&1 \
		&& sgdisk -g "$MEDIA" >> "$LOG" 2>&1 \
		&& yes |parted -s "$MEDIA" resizepart 1 100% >> "$LOG" 2>&1 \
		|| fatal "Error: write Jetson Nano image failed!!!"
	fi
fi

# Write the disk image to media
if [ -n "$IMAGE" ]; then
	echo "= Writing: "
	echo "= $IMAGE "
	echo "= To: $MEDIA ...."
	"$CAT" "$IMAGE" | dd of=$MEDIA bs=4M; sync; sleep 3
	echo "= Writing image complete!"
	partprobe "$MEDIA"
fi

# Create partitions
if [ -n "$ROOTFS" ]; then
	if [ -n "$MEDIATABLE" ]; then
		parted -s "$MEDIA" mktable "$MEDIATABLE" >> "$LOG" 2>&1 \
		|| fatal "Error: create partitions table $MEDIATABLE failed"
		
		if [ -n "$BBLPART" ]; then
			echo 'y' | sgdisk \
			  --new=1:2048:67583 --change-name=1:bootloader \
			  --typecode=1:"$BBL" "$MEDIA" >> "$LOG" 2>&1 \
			|| fatal "Error: create BBL partition failed"
      # (67583 + 1)*512/2^20
			START_SECTOR=33MiB
			ROOTPART_NUM=2
		fi
		
		if [ -n "$FIRMPART" ]; then
			echo 'y' | parted -s -a optimal "$MEDIA" \
			  mkpart primary fat16 2MiB 64MiB >> "$LOG" 2>&1 \
			|| fatal "Error: create FIRMPART partition failed"
			START_SECTOR=64MiB
			ROOTPART_NUM=2
		fi
		
		[ -n "$START_SECTOR" ] || START_SECTOR=2MiB
		[ -n "$END_SECTOR" ] || END_SECTOR=100%
		[ -n "$ROOT_PART" ] || ROOT_PART=1
		
		echo 'y' | parted -s -a optimal "$MEDIA" \
		  mkpart primary ext4 "$START_SECTOR" "$END_SECTOR" >> "$LOG" 2>&1 \
		|| fatal "Error: create ROOT partition failed"
	fi
	
	sleep 2
	
	if [ -n "$IMAGE_OUT" ]; then
		kpartx -a -s "$MEDIA"
		ROOTPART="/dev/mapper/$(basename "$MEDIA")p$ROOTPART_NUM"
	fi
	
	if [ -n "$FIRMPART" ]; then
		[ -n "$IMAGE_OUT" ] \
		&& FIRMPART="/dev/mapper/$(basename "$MEDIA")p1"
		echo 'y' | mkfs.fat $FIRMPART >> "$LOG" 2>&1 \
		|| fatal "Error: format FIRMPART partition failed"
	fi
	
	echo 'y' | mkfs.ext4 -m 5 -b 4096 -i 8192 -I 256 "$ROOTPART" >> "$LOG" 2>&1 \
	|| fatal "Error: format ROOT partition failed"
	
	if [ -n "$BOOTFLAG" ]; then \
		parted -s "$MEDIA" set "$ROOTPART_NUM" "$BOOTFLAG" on >> "$LOG" 2>&1 \
		|| "Error: set ROOT on $BOOTFLAG failed"
	fi
	
	echo "Partitions created successfully"
	# check to see how many partitions on the rootfs
	sleep 2
	partprobe "$MEDIA"
	if [ $? -ne 0 ]; then
		fatal "Error: create partitions failed!!!"
	fi
	# UID definition
	if [ "$FIRMPART" != "" ]; then
		FIRMPART_UID="$(blkid $FIRMPART |sed -E 's;.*\sUUID="([^"]*)".*;\1;')"
	fi
	ROOTPART_UID="$(blkid $ROOTPART |sed -E 's;.*\sUUID="([^"]*)".*;\1;')"

else
# check device Partition Table compliance target
	case "$SOCS" in
		Rockchips-*|*-riscv64)
			PARTTABLE=gpt
			;;
		*)
			PARTTABLE=msdos
			;;
	esac
	unset MEDIATABLE
	parted "${MEDIA}" print | grep gpt >> "$LOG" 2>&1 && MEDIATABLE="gpt"
	parted "${MEDIA}" print | grep msdos >> "$LOG" 2>&1 && MEDIATABLE="msdos"
	if [ "$PARTTABLE" != "$MEDIATABLE" ]; then
		fatal "Error: Partition Table not $PARTTABLE"
	fi
	unset TYPEFS
	parted "${MEDIA}${partsuffix}1" print | grep "fat" >> "$LOG" 2>&1 && TYPEFS="fat"
	if [ "$TYPEFS" = "" ]; then
		unset FIRMPART
		if [ "$SOCS" = bbl-riscv64 ]; then
			ROOTPART="${MEDIA}${partsuffix}2"
		else
			ROOTPART="${MEDIA}${partsuffix}1"
		fi
		if [ "$TARGET" = "rpi2" -o "$TARGET" = "rpi3" ]; then
			fatal "Error: Firmware partition not found!!!"
		fi
	else
		FIRMPART="${MEDIA}${partsuffix}1"
		ROOTPART="${MEDIA}${partsuffix}2"
	fi
fi

# make temp mount points
if [ "$FIRMPART" != "" ]; then
	TMPFIRM="$(mktemp -d --tmpdir 'firmpart.XXXXXXXX' 2>>"$LOG")"
	mount "$FIRMPART" "$TMPFIRM" >> "$LOG" 2>&1
	if [ $? -ne 0 ]; then
		fatal "Error: mount $FIRMPART $TMPFIRM failed!!!"
	fi
fi
if [ "$ROOTPART" != "" ]; then
	TMPROOT="$(mktemp -d --tmpdir 'rootpart.XXXXXXXX' 2>>"$LOG")"
	mount "$ROOTPART" "$TMPROOT" >> "$LOG" 2>&1
	if [ $? -ne 0 ]; then
		fatal "Error: mount $ROOTPART $TMPROOT failed!!!"
	fi
fi

sleep 1

# Write the disk rootfs to media
if [ "$ROOTFS" != "" ]; then
	echo "= Writing: "
	echo "= $ROOTFS "
	if [ -n "$IMAGE_OUT" ]; then
		echo "= To: $IMAGE_OUT ...."
	else
		echo "= To: $MEDIA ...."
	fi
	$TAR "$ROOTFS" -C "$TMPROOT"
	if [ $? -ne 0 ]; then
		fatal "Error: writing rootfs!!!"
	fi
	sync;
	echo "= Writing rootfs complete!"
fi

PREFIX="$TMPROOT"

# Update /etc/fstab
if [ "$FIRMPART_UID" != "" ]; then
	mkdir -p "$PREFIX"/mnt/FIRMPART
	echo "UUID=$FIRMPART_UID	/mnt/FIRMPART	vfat	ro	0 0" >> "$PREFIX"/etc/fstab
fi
if [ "$ROOTPART_UID" != "" ]; then
	if [ "$(cat "$PREFIX/etc/fstab" |grep -e '[[:space:]]/[[:space:]]')" ]; then \
		sed -i "s/LABEL=ROOT/UUID=$ROOTPART_UID/" "$PREFIX"/etc/fstab
	else
		echo "UUID=$ROOTPART_UID	/	ext4 relatime	1 1" >> "$PREFIX/etc/fstab"
	fi
fi

# Update extlinux.conf
if [ "$ROOTPART_UID" != "" -a -f "$PREFIX"/boot/extlinux/extlinux.conf ]; then
	sed -i "s/LABEL=ROOT/UUID=$ROOTPART_UID/" "$PREFIX"/boot/extlinux/extlinux.conf
fi

if [ "$TARGET" = "jetson-nano" ]; then
	echo "= Install drivers for Nvidia Jetson Nano"
	. "${BOARDDIR}/${TARGET}" >> "$LOG" 2>&1
	if [ $? -ne 0 ]; then
		fatal "Error: install drivers for Nvidia Jetson Nano failed!!!"
	fi
	final_exit
fi

if [ "$TARGET" = "rpi2" ]; then
	echo "= Install bootloader for Raspberry Pi 2"
	rm -f "$TMPFIRM"/kernel8.img
	cp -f "${PREFIX}"/usr/share/u-boot/rpi_3_32b/* "$TMPFIRM"/
	if [ $? -ne 0 ]; then
		fatal "Error: install bootloader for Raspberry Pi 2 (armh)!!!"
	fi
	final_exit
fi

if [ "$TARGET" = "rpi3" ]; then
	echo "= Install bootloader for Raspberry Pi 3"
	rm -f "$TMPFIRM"/kernel7.img
	cp -f "${PREFIX}"/usr/share/u-boot/rpi_3/* "$TMPFIRM"/
	if [ $? -ne 0 ]; then
		fatal "Error: install bootloader for Raspberry Pi 3 (aarch64)!!!"
	fi
	final_exit
fi

if [ "$SOCS" = bbl-riscv64 ]; then
	unset KERNEL
	KERNEL="$(readlink -e $PREFIX/boot/vmlinuz |sed 's;.*/;;')"
	if [ "$KERNEL" = "" ]; then
		fatal "Error: kernel not found"
	fi
	. "$BOARDDIR/$TARGET"
	if [ $? -ne 0 ]; then
		fatal "Error: install bootloader for $TARGET!!!"
	fi
	final_exit
fi

# determine uboot and write to disk
if [ "$TARGET" != "" ]; then
	if [ -d "${PREFIX}/usr/share/u-boot/${TARGET}" ]; then
		. "${BOARDDIR}/${TARGET}"
	else
		fatal "No U-Boot files found for $TARGET!!!"
	fi
fi

final_exit

