#!/bin/bash
#
# BigLinux Store
# www.biglinux.com.br
# By Bruno Gonçalves
# 03/01/2020
# License: GPL v2 or greater

#Translation
export TEXTDOMAINDIR="/usr/share/locale"
export TEXTDOMAIN=biglinux-grub-restore


DISK_SELECTED="$(cat /tmp/grub-disks-selected)"
DISK_NAME="$(grep "${DISK_SELECTED}" /tmp/grub-disks | cut -f3 -d" ")"
DISK_TABLE="$(grep "${DISK_SELECTED}" /tmp/grub-disks | cut -f4 -d" ")"
DISK_SIZE="$(grep "${DISK_SELECTED}" /tmp/grub-disks | cut -f2 -d" ")"
SELECTED_PARTITION="$(awk -F: '{ print $1}' /tmp/os-prober-selected)"
SELECTED_OS="$(awk -F: '{ print $2 " - " $3 }' /tmp/os-prober-selected)"
PARTITION_FORMAT="$(awk -F: '{ print $5 }' /tmp/os-prober-selected)"
UUID_PARTITION="$(awk -F: '{ print $6 }' /tmp/os-prober-selected | sed 's|UUID=||g')"

umount -l $SELECTED_PARTITION 2> /dev/null
umount -l /mnt 2> /dev/null

if [ "$PARTITION_FORMAT" = "btrfs" ];
then
    mount $SELECTED_PARTITION -o subvol=@ /mnt
else
    mount $SELECTED_PARTITION /mnt
fi

if [ "$(cat /tmp/grub-restore-apply-mode)" = "1" ];
then
    grub-install --root-directory=/mnt /dev/${DISK_SELECTED}
fi

if [ "$(cat /tmp/grub-restore-apply-mode)" = "2" ];
then
    manjaro-chroot /mnt rm /var/lib/pacman/db.lck
    manjaro-chroot /mnt pacman --noconfirm -Sy grub
    manjaro-chroot /mnt grub-install --force --target=i386-pc --recheck --boot-directory=/boot /dev/${DISK_SELECTED}
    manjaro-chroot /mnt mkinitcpio -P
    manjaro-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg
fi


if [ "$(cat /tmp/grub-restore-apply-mode)" = "3" ];
then
    manjaro-chroot /mnt rm /var/lib/pacman/db.lck
    manjaro-chroot /mnt pamac update --force-refresh --no-confirm
    manjaro-chroot /mnt pamac install linux grub --no-confirm
    manjaro-chroot /mnt pacman --noconfirm -Syyuu grub
    manjaro-chroot /mnt pacman --noconfirm -Syyuu linux
    manjaro-chroot /mnt grub-install --force --target=i386-pc --recheck --boot-directory=/boot /dev/${DISK_SELECTED}
    manjaro-chroot /mnt mkinitcpio -P
    manjaro-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg
fi

if [ "$(cat /tmp/grub-restore-apply-mode)" = "4" ];
then
    manjaro-chroot /mnt bash
fi

if [ "$(cat /tmp/grub-restore-apply-mode)" = "5" ];
then
    manjaro-chroot /mnt bigcontrolcenter
fi

if [ "$(cat /tmp/grub-restore-apply-mode)" = "6" ];
then
    manjaro-chroot /mnt rm /var/lib/pacman/db.lck
    manjaro-chroot /mnt pamac-manager
fi

echo "sync disk"
sleep 1
echo "umount /mnt/boot"
umount /mnt/boot 2>/dev/null
sleep 1
echo "umount /mnt"
umount /mnt 2>/dev/null
sleep 1
