#!/bin/bash

set -x

exec >> /var/log/generate-recovery-iso.log 2>&1

BASE="$(mktemp -d)"
AUFS="$(mktemp -d)"
UUID="$(uuidgen -r)"

if [ "$1" = "--oobe" ]; then
    mount --bind /cdrom "$BASE"
else
	RPLB=$(echo "get ubuntu-recovery/recovery_hotkey/partition_label" | debconf-communicate | cut -d" " -f 2)
	if [ -z "${RPLB}" ]
	then
		echo "recovery partition label not found"
		exit 1
	fi

	rpdev=$(blkid -L "${RPLB}")
	if [ -z "${rpdev}" ]; then
		rpdev=$(blkid -t PARTLABEL="Recovery Partition" -o device)
		if [ -z "${rpdev}" ]; then
			echo "recovery partition device not found"
			exit 1
		fi
	fi

    mount -v -t vfat -r "${rpdev}" "$BASE"
fi

cp -rf "$BASE"/. "$AUFS"
mv -v "$AUFS"/boot/grub/grub.cfg.old "$AUFS"/boot/grub/grub.cfg
rm -f "$AUFS"/boot/grub/grubenv

# .disk/casper-uuid* will be checked by the script in initramfs
# casper-uuid-$TYPE, casper-uuid-"${LB_LINUX_FLAVOURS} or casper-uuid
echo "$UUID" | tee "$AUFS"/.disk/casper-uuid* > /dev/null
INITRD="$(mktemp -d)"
cd "$INITRD" || exit
/usr/bin/unmkinitramfs "$AUFS"/casper/initrd .

# get compress method in initramfs
new_compress=$(grep "COMPRESS=" main/conf/initramfs.conf | awk -F"=" '{print $2}')
compress_command=""
if [ "$new_compress" == "gzip" ]; then
	compress_command="gzip -n"
elif [ "$new_compress" == "lzma" ] || [ "$new_compress" == "xz" ]; then
	compress_command="xz --check=crc32"
elif [ "$new_compress" == "lz4" ]; then
	compress_command="lz4 -9 -l"
elif [ "$new_compress" == "zstd" ]; then
    compress_command="zstd -q -1 -T0"
else
    echo "Unknown compress method ${new_compress}."
    exit 255
fi
#lzma -cd $AUFS/casper/initrd.lz -S lz | cpio -id
echo "$UUID" > main/conf/uuid.conf

:> "$AUFS"/casper/initrd
for component in 'early' 'early2' 'main';
do
	if [ $component == "main" ]; then
		(cd $component; find | cpio --quiet -o -H newc | $compress_command >> "$AUFS"/casper/initrd)
	else
		(cd $component; find | cpio --quiet -o -H newc  >> "$AUFS"/casper/initrd)
	fi
done	

cd - || exit
rm -fr "$INITRD"

if [ -d /sys/firmware/efi ]; then
    # efi mode
    # yuning: TODO: remove legacy support?

    if [ -f "$AUFS"/EFI/boot/shimx64.efi ]; then
        mv -v "$AUFS"/EFI/boot/shimx64.efi "$AUFS"/EFI/boot/bootx64.efi
    fi
else
    # legacy mode, remove efi support
    rm -rf "$AUFS"/boot/grub
    rm -rf "$AUFS"/boot/efi.img
    rm -rf "$AUFS"/efi/
fi

mkdir -p /usr/share/ubuntu/

# We have preserved one efi.img under /boot dir, we can use it to 
# create UEFI/Legacy hybrid ISO.
xorriso \
    -volid "Ubuntu Recovery Media" \
    -publisher "Canonical Ltd." \
    -application_id "Ubuntu Recovery" \
    -preparer_id "Ubuntu" \
    -as mkisofs -J -joliet-long -l \
    -b boot/grub/i386-pc/eltorito.img -no-emul-boot \
    -boot-load-size 4 -boot-info-table \
    --grub2-boot-info \
    --grub2-mbr /usr/share/cd-boot-images-amd64/images/boot/grub/i386-pc/boot_hybrid.img \
    -append_partition 2 0xef /usr/share/cd-boot-images-amd64/images/boot/grub/efi.img -appended_part_as_gpt \
    --mbr-force-bootable -eltorito-alt-boot -e --interval:appended_partition_2:all:: -no-emul-boot \
    -partition_offset 16 -r ${AUFS} \
    -volset "$(tail -1 /etc/buildstamp)" \
    -o /usr/share/ubuntu/recovery.tmp
rm -rf "$AUFS"
umount "$BASE"
rmdir "$BASE"
mv /usr/share/ubuntu/recovery.tmp /usr/share/ubuntu/recovery.iso
