#!/bin/ash
#
#
#
 . /usr/share/grub/mini/getname.sh
 RDEV=/dev/ram0
 if [ -e /etc/rootfs ]; then
   RDEV=$(cat /etc/rootfs)
 fi
 if [ $RDEV = /dev/ram0 ]; then
   echo "$NAME must be installed to a HDD."
   echo "Bye!"
   exit
 fi
 grub-mini $RDEV
 clear
 echo "This will install GNU GRUB for you."
 echo "*** GRUB will replace your existing $BOOT boot loader!!! ***"
 read -p "Do you wish to continue (y/n)?: " ANSWER
 ANSWER=Y$ANSWER
 REFIND=no
 if [ $ANSWER = Yy ]; then
   if [ -e /sys/firmware/efi ]; then
     echo ""
     read -p "Should I also install the rEFInd boot manager (y/n)?: " REFIND
     REFIND=Y$REFIND
   fi
   if [ ! -e /opt/grub ]; then
     URL=https://www.dropbox.com/s/5ikz9zcmir7hvwz/
     FILE=addon_grub.tar.xz
     rm -f /tmp/$FILE 2>/dev/null
     echo "Downloading GRUB:"
     curl --connect-timeout 5 -#Lk $URL$FILE > /tmp/$FILE
     file /tmp/$FILE | grep XZ > /tmp/$FILE.tmp
     if [ ! -s /tmp/$FILE.tmp ]; then
       rm /tmp/$FILE
       rm /tmp/$FILE.tmp
       URL=http://dl.4mlinux.com/
       FILE=addon_grub.tar.xz
       /usr/share/busybox/wget $URL$FILE -P /tmp
     fi
     if [ ! -e /tmp/$FILE ]; then
       echo "Error in downloading. Check your internet connection."
       if [ ! x$DISPLAY = x ]; then
         sms "You can find GRUB on the 4MLinux installation CD."
         echo "You can close this window now."
       fi
       exit
       else
       rm /tmp/$FILE.tmp 2>/dev/null
       rm -r /etc/grub.d 2>/dev/null
       rm -r /usr/lib/grub 2>/dev/null
       rm -r /usr/share/refind 2>/dev/null
       zk.sh /tmp/addon_grub.tar.xz
       rm /tmp/addon_grub.tar.xz
     fi
   fi
   cd /boot
   rm map 2>/dev/null
   rm vmlinuz-* 2>/dev/null
   ln -s bzImage vmlinuz-$NAME
   clear
   if [ -e /var/log/nvme.log ]; then
     grub-install --no-nvram /dev/nvme0n1
     else
     if [ -e /sys/firmware/efi ]; then
       grub-install --no-nvram /dev/sda
       else
       grub-install /dev/sda
     fi
   fi
   grub-mkconfig -o /boot/grub/grub.cfg
   if [ -e /sys/firmware/efi ]; then
     mkdir /boot/efi/EFI/boot 2>/dev/null
     if [ $REFIND = Yy ]; then
       cp -r /usr/share/refind/* /boot/efi/EFI/boot
       else
       cp /boot/efi/EFI/grub/grubx64.efi /boot/efi/EFI/boot/bootx64.efi 2>/dev/null
       cp /boot/efi/EFI/grub/grubia32.efi /boot/efi/EFI/boot/bootia32.efi 2>/dev/null
     fi
     rm -r /boot/efi/.disk
     rm /boot/efi/boot/bzImage
     rm -r /boot/efi/boot/grub
   fi
   if [ ! x$DISPLAY = x ]; then
     echo "You can close this window now."
     else
     echo "Bye!"
   fi
 fi
