#!/bin/bash
#
# test restoring efi grub on a test vm

PASSWORD="${PASSWORD}"
set -xe

devices=(
	/dev/vda4
#	/dev/sdb4
#	/dev/sda2
#	/dev/sdb2
)
names=(
	btrfs
#	btrfs1
#	btrfs_boot
#	btrfs1_boot
)

for index in {0..2} ; do
	expname="${names[index]}"
	if [[ -e /dev/mapper/$expname ]]; then
		continue
	fi
	echo "${PASSWORD}" | cryptsetup luksOpen "${devices[index]}" "$expname" 
done

mkdir -p /target
if ! mount | grep -F /target; then
	mount -o subvol=@ "/dev/mapper/${names[0]}" /target
	mount /dev/vda2 /target/boot
	#for i in /dev /dev/pts /proc /sys /sys/firmware/efi/efivars /run; do
	for i in /dev /dev/pts /proc /sys /run; do
		mount -B $i /target/$i
	done
fi
#mount /dev/vda1 /target/boot/efi
chroot /target grub-install /dev/vda
chroot /target update-grub2
sync
echo "SUCCESS"
