#!/usr/bin/env bash
# update-init-crypt.sh

#set -x


select_device () {

	usbdevlist=$(/usr/sbin/hwinfo --usb --short|grep "/dev/sd"|awk '{print $1}')
	usbdevfulllist=$(/usr/sbin/hwinfo --usb --short|grep "/dev/sd"|awk '{print $0}')

	echo -e "\n\tLIST OF USB DEVICES\n\n$usbdevfulllist\n\nSelect by number"
	select opt in $usbdevlist ; do
		device="$opt"
		break
	done

}

select_initrd () {
	
	echo -e "\n Select the initrd for the currently running system"
	initrd_list=$(find /boot -type f -name "init*")
	select file in $initrd_list ; do
		system_initrd="$file"
		break
	done

}


# Check for cryptsetup, check that root is running the script.
check_commands () {

	if [[ $(id -u) -ne 0 ]] ; then
		echo -e "\n\tYou need to be root!\n"
		exit 1
	fi
	
	if ! type -p cryptsetup ; then
		echo "cryptsetup is not installed. You can only use unencrypted persistence.
	
See the Help section on Encryption
"
		exit 1

	fi

}


update_initrd () {

#	 Copy/Rename updated initrd to target_dir
	read -p "  Enter or change the name of the updated initrd: " -i initrd.crypt -e initrd_name

#	 if live-tools is installed, use the original update-initramfs
	if [ -f /usr/sbin/update-initramfs.orig.initramfs-tools ] ; then
		CRYPTSETUP=y /usr/sbin/update-initramfs.orig.initramfs-tools -u
	else
		CRYPTSETUP=y update-initramfs -u
	fi

	cp "$system_initrd"  ${target}/${initrd_name}

}



select_target () {
	
	dirlist=$(ls "$live_media_dir" | awk '{ print $0 }')
	echo -e "\nSelect the target directory for the updated initrd.\n(i.e. The named directory for the live system.)\n"
	select dir in $dirlist ; do
		target_dir="$dir"
		break
	done
	
	### if using findiso, there is no target_dir/live
	if [ -d "${live_media_dir}/${target_dir}/live" ] ; then
		target="${live_media_dir}/${target_dir}/live"
	else
		target="${live_media_dir}/$target_dir"
	fi

}



######### The work starts here. ############



check_commands
select_device


# Find where the live media is mounted
if [[ -e /lib/live/mount/persistence/"${device##*/}1" ]] ; then
	live_media_dir="/lib/live/mount/persistence/${device##*/}1"
elif [[ -e /lib/live/mount/medium ]] ; then
	live_media_dir="/lib/live/mount/medium"
else
	echo "Can't find live media mount point.  Exiting..."
	exit 1
fi


# Can use select_initrd function here to choose from initrds in /boot
# instead of defining it to use /initrd.img.
system_initrd=$(ls -l /initrd.img | awk -F"> " '{ printf $2 }')


select_target
update_initrd


# edit boot menu.
filelist=$(ls ${live_media_dir}/syslinux | awk '{ print $0 }')
echo -e "\nSelect the boot menu. (maybe live.cfg or menu.txt)\n"
select file in $filelist ; do
	boot_menu="$file"
	break
done
nano ${live_media_dir}/syslinux/"$boot_menu"


exit 0
