#!/bin/sh

mkdir -p /boot/imgs

# Backup the previous metadata
/usr/bin/metadata -v cdrom
mv /boot/imgs/fickit-metadata.iso /boot/imgs/fickit-metadata.iso.bak

for img in fickit-boot-kernel fickit-metadata.iso fickit-boot-initrd.img fickit-prepare-initrd.img fickit-frontend-squashfs.img fickit-backend-squashfs.img fickit-update-initrd.img
do
    wget -O "/boot/imgs/${img}" "$1/${img}"
done

# Check dm-crypt key not changed
ISO=$(mktemp -d)
mount /boot/imgs/fickit-metadata.iso "${ISO}"

NEW_KEY=$(sed -rn 's/.*"content": "([^"]+)"$/\1/p' "${ISO}/user-data" | head -n 1)
OLD_KEY=$(cat /run/config/dm-crypt/key)

[ "${NEW_KEY}" != "${OLD_KEY}" ] && {
    read -p "DM-CRYPT key changed in metadata, are you sure you want to erase it? (y/N) " V
    [ "$V" != "y" ] && [ "$V" != "Y" ] && while true; do
        echo
        echo "Metadata drive not erased"
        echo
        /bin/ash
        sync
        reboot -f
    done
}

umount "${ISO}"

dd if=/boot/imgs/fickit-metadata.iso of="$2"
