#!/bin/bash

set -x
echo "Factory-reset: update from recovery .. "
RECOVERY_PART=`blkid | grep recovery | cut -f1 -d':' | head -1`
echo "Recovery partition: ${RECOVERY_PART}"

systemctl stop NetworkManager.service
systemctl stop networking
mount ${RECOVERY_PART} /mnt/
ls /mnt

rescue_vmlinuzname=`find /mnt/boot -name "vmlinuz-*generic" | head -1`
rescue_initrdname=`find /mnt/boot -name "initrd*generic" | head -1`
rescue_cmdline=`cat /mnt/boot/grub/grub.cfg | grep UUID | head -1| cut -f2- -d" "`

echo "#!/bin/bash
chmod 644 /etc/rc.local
umount /boot/efi
DISK_DEV=\`blkid | grep recovery | cut -f1 -d':'| sed 's/p[0-9]//' | sed 's/a[0-9]/a/' | sed 's/b[0-9]/b/' | sed 's/c[0-9]/c/' | head -1\`
echo \"Disk device: \${DISK_DEV}\"
umount \${DISK_DEV}p2
umount \${DISK_DEV}2
umount /dev/astramvg/optvol
umount /dev/astramvg/homevol
umount /dev/astramvg/rootvol
sync
/opt/astra-mobile-install -f -s -d \${DISK_DEV}
sync
reboot
" > /mnt/etc/rc.local
chmod 755 /mnt/etc/rc.local
sync

nextboot=`efibootmgr | grep Recovery | cut -f1 -d'*' | sed 's/Boot//'`
echo "next boot: ${nextboot}"
if [[ ! -z "${nextboot// }" ]] ; then
    efibootmgr -n ${nextboot}
    umount -a
    reboot
else
    kexec -l ${rescue_vmlinuzname} --initrd=${rescue_initrdname} --command-line=${rescue_cmdline}
    kexec -e
fi
