#!/usr/bin/sh

#
# Hybrid Appliance eUSB/SATA-DOM maintenance tool
#
# Copyright © 2026 Musarubra US LLC, d.b.a. Skyhigh Security
#

#############################################################
# Main
#############################################################

if [ "$(id -u)" -ne 0 ]; then
    exec sudo -n -- "$0" "$@"
fi

LOG_FILE="/var/log/hyb-edisk.log"

edisk_usage() {
	echo "usage: hyb-edisk <command> [option]" | tee -a $LOG_FILE
	echo "" | tee -a $LOG_FILE
	echo "    commands:" | tee -a $LOG_FILE
	echo "        check <file>        - check ISO image" | tee -a $LOG_FILE
	echo "        info                - show embedded drive info and status" | tee -a $LOG_FILE
	echo "        list                - show embedded drive info and status" | tee -a $LOG_FILE
	echo "        write <file>        - write image file to embedded drive" | tee -a $LOG_FILE
}

edisk_main() {
	local command=$1
	local arg1=$2
	if [ -z "$command" ];then
	   	edisk_usage
		exit 1
	fi
	
	echo "***hyb-edisk log start***" >> $LOG_FILE
	date >>$LOG_FILE
	echo "*************************"  >> $LOG_FILE
	case $command in
		write)
			if [ -z "$arg1" ]; then
				edisk_usage
				exit 1
			fi
			edisk_write "$arg1"
			;;
		check)
			if [ -z "$arg1" ]; then
				edisk_usage
				exit 1
			fi
			edisk_check "$arg1"
			;;
		info)
			edisk_info
			;;
		list)
			edisk_info
			;;
	esac
}

CLEANUP_DEVNODES=""

cleanup_mountpoints() {
    local max_tries=3

	debug "Cleaning up mountpoints for devices: $CLEANUP_DEVNODES"
	for devnode in $CLEANUP_DEVNODES; do
		local tries=0
		while [ $tries -lt $max_tries ]; do
			# Removing empty lines; in case of NVME the namespace 
			# device is queried for the mountpoints, which is bound to return
			# empty lines
			local mountpoints=""
			if [ -b "$devnode" ]; then
				mountpoints=$(lsblk "$devnode" -o MOUNTPOINT -n | awk 'NF')
			elif [ -f "$devnode" ]; then
				mountpoints=$(mount | grep "$devnode" | awk '{print $3}')
			fi

			if [ -z "$mountpoints" ]; then
				debug "No mountpoints found for $devnode, skipping unmount."
				break
			fi
			debug "Found mountpoints for $devnode: $mountpoints"

			# When saving the mounts in a variable, each mount point is separated by a single space
			# Not caring about mount points with spaces in them as we only mount on directories 
			# returned from `mktemp -d` which does not return directories with spaces in it
			local mountpoint=$(echo $mountpoints | cut -d' ' -f1)

			# Running `umount -A` on the mount point itself, rather than on the device node
			# as for NVME devices the namespace(nvme0n1) is passed not the partition(nvme0n1p1),
			# and running umount on the namespace fails because partitions are mounted not the namespace
			if umount -A $mountpoint 2>/dev/null; then
				debug "Successfully unmounted $mountpoint for $devnode"
				rmdir $mountpoints || warn "Failed to remove mountpoint directory $mountpoints, manual cleanup required"
			fi
			tries=$((tries+1))
		done
		if [ $tries -ge $max_tries ]; then
			err "Unable to cleanup mountpoints for $devnode"
		else
			debug "Cleaned up mountpoints for $devnode"
		fi
	done
}

writeIsoImage() {
	local device="$1"
	local image="$2"

	local efiDir="$(mktemp -d)"
	local isoDir="$(mktemp -d)"
	local ediskDir="$(mktemp -d)"

	if [ ! -d "$efiDir" ] || [ ! -d "$isoDir" ] || [ ! -d "$ediskDir" ]; then
		rm -f "$efiDir" "$isoDir" "$ediskDir"
		err "Failed to create temporary directories."
	fi

	trap cleanup_mountpoints EXIT SIGINT SIGTERM

	debug "Mounting ISO image $image to $isoDir"
	mount "$image" "$isoDir" >/dev/null 2>&1 || err "Failed to mount ISO image."
	CLEANUP_DEVNODES="$image $CLEANUP_DEVNODES"

	if [ -d "$isoDir/EFI/slos" ]; then
		if ! command -v mkfs.vfat >/dev/null 2>&1; then
			if ! command -v busybox >/dev/null 2>&1; then
				err "mkfs.vfat not found. Cannot continue"
			else
				debug "mkfs.vfat not found, but busybox is available. Creating symlink for mkfs.vfat."
				ln -s "$(command -v busybox)" /sbin/mkfs.vfat || err "Failed to create symlink for mkfs.vfat"
			fi
		fi

		debug "ISO contains EFI directory. Preparing to copy EFI bootloader."
		mount "$isoDir/isolinux/efiboot.img" "$efiDir" >/dev/null 2>&1 || err "Failed to mount efiboot.img."
		CLEANUP_DEVNODES="$isoDir/isolinux/efiboot.img $CLEANUP_DEVNODES"

		parted "$device" -s mklabel gpt || err "Failed to create GPT label on $device."
		parted "$device" -a optimal -s mkpart primary fat32 1MiB 100% || err "Failed to create partition on $device."
		parted "$device" -s set 1 boot on || err "Failed to set boot flag on partition 1 of $device."

		local partition=""
		if [[ "$device" =~ ^/dev/nvme ]]; then
			partition="${device}p1"
		else
			partition="${device}1"
		fi

		# TODO: Change this to have a separate ESP and partition that contains the installation files
		# It won't be an issue until any one of the files is larger than 4GB, which is the limit for FAT32.
		# For now, we can just copy all the files to the ESP partition.
		debug "Formatting $partition as FAT32 and mounting to $ediskDir"
		mkfs.vfat -F 32 "$partition" >/dev/null 2>&1 || err "Failed to format $partition as FAT32."
		mount "$partition" "$ediskDir" >/dev/null 2>&1 || err "Failed to mount $partition."
		CLEANUP_DEVNODES="$partition $CLEANUP_DEVNODES"

		debug "Copying ISO contents and EFI bootloader to $device"
		cp -rL "$isoDir/." "$ediskDir/" || err "Failed to copy ISO contents to $device."
		cp -rL "$efiDir/." "$ediskDir/" || err "Failed to copy EFI bootloader to $device."
	else
		debug "ISO does not contain EFI directory. Writing ISO image directly to $device using dd."
		run dd if="$image" bs=1M of="$device" status=progress
	fi

	udevadm settle
}

############################################################
# Commands
############################################################

edisk_check() {
	local image="$1"
	if [ ! -r "$image" ]; then
		err "file not found ($image)"
	fi
    # TODO: Add the ED25519 signature to the Hybrid ISO
    # Changes to /etc/signify would also be required
	if /usr/bin/checkisomd5 "$image" >/dev/null 2>&1; then
		echo "Verification result: PASS" | tee -a $LOG_FILE
		exit 0
	else
		echo "Verification result: FAIL" | tee -a $LOG_FILE
		exit 1
	fi
}

edisk_write() {
	local image="$1"
	if [ ! -r "$image" ]; then
		err "file not found ($image)"
	fi
	local disk=$(edisk_find_disk)
	if [ -z "$disk" ]; then
		err "no embedded disk device found"
	fi
	local device="/dev/$disk"
	if [ ! -e $device ]; then
		err "no embedded disk device node found"
	fi
	if ! /usr/bin/checkisomd5 "$image" >/dev/null 2>&1; then
		err  "ISO verification failed"
	fi
	echo "ISO verification result: PASS" | tee -a $LOG_FILE
	echo "Writing to: $device" | tee -a $LOG_FILE

	writeIsoImage "$device" "$image"

	echo "Transfer complete." | tee -a $LOG_FILE
	exit 0
}

edisk_info() {
	local substring="nvme"
	local disk=$(edisk_find_disk)

	if [ -z "$disk" ]; then
		err "no embedded disk device found"
	fi

	local device="/dev/$disk"
	if [ ! -e "$device" ]; then
		err "no embedded disk device node found"
	fi

	local mount_point=$(mktemp -d)
	if [ -z "$mount_point" ]; then
		err "Failed to create a temporary mount point."
	fi

	# Trap for robust cleanup. This will unmount and remove the directory
	# even if the script fails or is interrupted.
	CLEANUP_DEVNODES="$device $CLEANUP_DEVNODES"
	trap cleanup_mountpoints EXIT SIGINT SIGTERM

	local file_found=""

	if [[ "$device" =~ "$substring" ]]; then
		local part_num="1"
		local device_part=""
		if [[ "$disk" =~ ^(nvme|mmcblk) ]]; then
			device_part="${device}p${part_num}"
		else
			device_part="${device}${part_num}"
		fi

		# Attempt to mount the VFAT partition
		if ! sudo mount -t vfat "$device_part" "$mount_point" &>/dev/null; then
			err "Failed to mount NVMe ESP partition: $device_part"
		fi
	else
		# Mount the non-NVMe (raw ISO)
		if ! sudo mount -t iso9660 -o ro "$device" "$mount_point" &>/dev/null; then
			err "Failed to mount raw ISO device: $device"
		fi
	fi

    if [ ! -e "$mount_point/ID" ]; then
        err "Version on embedded disk: unknown"
    fi

    version="$(awk 'match($0, /(.*)-x86_64.iso/, ver) {print ver[1]}' $mount_point/ID)"
    echo "Version on embedded disk: $version" | tee -a "$LOG_FILE"
}

#############################################################
# Helper functions
#############################################################

err() {
	echo "error: $*" 1>&2  | tee -a $LOG_FILE
	exit 1
}

warn() {
	echo "warning: $*" 1>&2 | tee -a $LOG_FILE
}

debug() {
	if [ -n "$DEBUG" ]; then
		echo "debug: $*" 1>&2 | tee -a $LOG_FILE
	fi
}

# run command and exit on error
run() {
	local status
	debug "$*"
	LIBC_FATAL_STDERR_=1 MALLOC_CHECK_=3 $*
	status=$?
	if [ $status -ne 0 ]; then
		err "$* failed with $status"
	fi
}

# run command with redirected output and exit on error
runx() {
	local status
	debug "$*"
	LIBC_FATAL_STDERR_=1 MALLOC_CHECK_=3 $* >/dev/null 2>&1
	status=$?
	if [ $status -ne 0 ]; then
		err "$* failed with status $status"
	fi
}

#
# check that size of device is greater than given min
# and optionall smaller than given max
# device: sysfs device name (e.g. hda, sda, vda)
# min:    minimum size in MiB
# max:    maximum size in MiB (default: unlimited)
#
edisk_check_size() {
	local device=$1
	local min=$2
	local max=$3
	size=$(( $(cat /sys/block/$device/size) / 2048))
	if [ $size -lt $min ]; then
		debug "edisk_check_size: $device too small (size: $size, min: $min, max: $max)"
		return 1
	elif [ -n "$max" -a $size -ge $max ]; then
		debug "edisk_check_size: $device too big (size: $size, min: $min, max: $max)"
		return 1
	else
		debug "edisk_check_size: $device within limits (size: $size, min: $min, max: $max)"
		return 0
	fi
}

#
# search disks in pre-defined order
#
# minimum: minimum size in MB for the disk
# maximum: maximum size in MB for the disk
#
edisk_find_disk() {
	local product=$(dmidecode -s system-product-name)
	local minimum="10000"
	local maximum="64000"
	local selector=""

	case $product in
		Appliance\ D1|Appliance\ D2)
			selector='/usb1/1-8/'
			;;
		Appliance\ D3*)
			selector='/ata1/host0/'
			;;
		Appliance\ F[1-2])
			selector='/nvme0n1'
			maximum="115000"
			;;
		*)
			err "platform not supported: $product"
			;;
	esac
	debug "edisk_find_disk: minimum=$minimum maximum=$maximum selector=$selector"

	local disk=""
	for disk in sda sdb sdc sdd sde sdf sdg sdh nvme0n1; do
		if [ ! -e /sys/block/$disk ]; then
			debug "edisk_find_disk: $disk does not exist"
			continue
		fi
		local path="$(readlink /sys/block/$disk)"
		if ! echo $path | grep -q "$selector" ; then
			debug "edisk_find_disk: $disk does not match selector $selector"
			debug "edisk_find_disk: $disk path: $path"
			continue
		fi

		if edisk_check_size $disk $minimum $maximum; then
			debug "edisk_find_disk: found $disk"
			echo $disk | tee -a $LOG_FILE
			return
		fi
	done

	debug "edisk_find_disk: no disk found"
	echo ""
}


edisk_main $*