#!/bin/sh

# $MTPT  chroot Ƥ¹Ԥʬ

PROBE=/sbin/fdisk
crunch () { # remove extra whitespace
    read STRING;
    echo $STRING
}

ROOT_DEVICE=`cat /tmp/grub_ROOT_DEVICE`
ROOT_DISK=`cat /tmp/grub_ROOT_DISK`
EFI_PART=`LANG=C ; fdisk -l $ROOT_DISK | grep EFI | cut -f1 -d' '`

if [ "$EFI_PART.x" = ".x" ]; then
    if [ -f /tmp/ESP_partition ]; then
	EFI_PART=`cat /tmp/ESP_partition`
    fi
    if [ "$EFI_PART.x" = ".x" ]; then
	/bin/dialog --title "cannot find EFI partition" --msgbox \
		"${ROOT_DISK}ˤEFIѤΥѡƥ󤬸ĤޤǤ\
                 EFIѡƥäƤ뤫åƤ" 8 70
	exit 1
    else
	/bin/dialog --title "use other HDDs EFI partition" --yesno \
		    "${ROOT_DISK}ǤϤʤ${EFI_PART}EFI System PartitionȤѤޤפǤ" 8 70
	if [ $? -ne 0 ]; then
	    /bin/dialog --title "grub install abondoned" --msgbox \
		"GRUB2Υ󥹥ȡߤޤΤޤޤǤϥƥưǤʤΤǡPlamoΥ󥹥ȡǺƵưƤ" 8 70
	    exit 1
	fi
    fi
fi

if [ ! -d /boot/efi/EFI ]; then
    if [ ! -d /boot/efi ]; then
	mkdir /boot/efi
    fi
    mount $EFI_PART /boot/efi
    if [ $? -ne 0 ]; then
	/bin/dialog --title "cannot mount EFI partition" --msgbox \
		    "EFIƥѥѡƥ($EFI_PART)ޥȤǤޤǤΤޤޤǤϥƥưǤʤΤǡPlamoΥ󥹥ȡǺƵưƤ" 6 70
	exit 1
    fi
fi
    
/bin/dialog --title "grubΥ󥹥ȡ(1)" --infobox \
    "grub${EFI_PART}˥󥹥ȡ뤷Ƥޤ" 6 70

arch=`uname -m`
if [ "$arch" = "x86_64" ]; then
    grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=grub --boot-directory=/boot/efi --recheck
else
    grub-install --target=i386-efi --efi-directory=/boot/efi --bootloader-id=grub --boot-directory=/boot/efi --recheck
fi

if [ $? -ne 0 ]; then
    /bin/dialog --title "grub install error" --msgbox \
	"${EFI_PART}grubinstallǤޤǤ \
꤬褦ʤΤǽǤޤΤޤޤǤϥƥưǤʤΤǡPlamoΥ󥹥ȡǺƵưƤ" 6 70
    exit 1
fi
sleep 3

/bin/dialog --title "grubΥ󥹥ȡ(2)" --infobox \
    "grub.cfg${EFI_PART}/grub˺Ƥޤ" 6 70

LANG=C
grub-mkconfig -o /boot/efi/grub/grub.cfg
LANG=ja_JP.eucJP
if [ $? -ne 0 ]; then
    /bin/dialog --title "grub.cfg install error" --msgbox \
	"/boot/efi/grub/grub.cfg ǤޤǤ \
         ꤬褦ʤΤǽǤޤΤޤޤǤϥƥưǤʤΤǡPlamoΥ󥹥ȡǺƵưƤ" 6 70
    exit 1
fi

sleep 3
# BIOSˤäƤ /EFI/BOOT/bootx64.efi ǤˤʤäƤΤ⤢
# (ex: VirtualBox)


if [ "$arch" = "x86_64" ]; then
    if [ ! -d /boot/efi/EFI/BOOT ]; then
        mkdir /boot/efi/EFI/BOOT
        cp /boot/efi/EFI/grub/grubx64.efi /boot/efi/EFI/BOOT/bootx64.efi
    fi
else
    if [ ! -d /boot/efi/EFI/BOOT ]; then
        mkdir /boot/efi/EFI/BOOT
        cp /boot/efi/EFI/grub/grub.efi /boot/efi/EFI/BOOT/boot.efi
    fi
fi


if [ $? != 0 ]; then
    dialog --title "install failed" --msgbox \
	   "grub${EFI_PART}˥󥹥ȡǤޤǤ\
ΤޤޤǤϥƥưǤʤΤǡPlamoΥ󥹥ȡǺƵưǧƤ" 10 70
    exit 1
fi

if [ -x /sbin/grub_partuuid.sh ]; then
    dialog --title "convert root device name?" --yesno \
	   "grub.confroot device̾ѡƥUUIDѴޤ \
ѡƥUUIDHDDǧ˱ƶʤΤǡ \
USBޤޤ޵ưHDDߤƤפǤ \
ʤνϺƵư /sbin/grub_partuuid.sh ưƤ¹ԤǤޤ" 10 70
    if [ $? -eq 0 ]; then
	/sbin/grub_partuuid.sh
	if [ $? -eq 0 ]; then
	    dialog --title "grub.conf converted" --msgbox \
		   "ѡƥUUIDȤ褦grub.cfgޤ" 10 70
	fi
    fi
fi
