#!/bin/sh

expand_mes() {
    mnt_chk=`echo $0 | grep '/mnt'`
    if [ "$mnt_chk.x" != ".x" ]; then
        MNT="/mnt"
    fi
    source $MNT/sbin/grubconfig.mes
}

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

expand_mes
# インストール直後なら必要な情報は/tmpから取れる
if [ -f /tmp/SeTT_PX -a -f /tmp/SeTrootdev ] ; then  
    # 2024/01/11 
    # /var/log/setup/setup.bootloader を廃し、initpkgから実行するようにしたので、
    # インストール直後でも chroot してからの実行になるため MTPTは "/" になる
    # MTPT=`cat /tmp/SeTT_PX`
    MTPT="/"
    ROOT_DEVICE=`cat /tmp/SeTrootdev`
else
    CURRENT_ROOT_DEVICE=`grep " / " /etc/fstab | cut -f1 -d' '`
    expand_mes
    /bin/dialog --title "select directory for grub (1)" --yesno "$dir_mes_1" 10 70

    if [ $? = 0 ]; then
	MTPT="/"
	ROOT_DEVICE=$CURRENT_ROOT_DEVICE
    else
        # 現在の root partition とは違うところにgrubをインストール
	/bin/dialog --title "select directory for grub (2)" --yesno "$dir_mes_2" 18 74

	if [ $? -ne 0 ] ;then
	    exit
	fi

	/bin/dialog --title "select directory for grub (3)" --inputbox \
	    "$dir_mes_3" 10 74 2> /tmp/return
	if [ $? = 255 -o $? = 1 ]; then   # user break
	    exit 1
	fi
	MTPT=`cat /tmp/return`
	rm /tmp/return
        # check $MTPT
	if [ "$MTPT.x" = ".x" ] ; then
	    /bin/dialog --title "Error: no mountpoint" --msgbox "$no_mpt_mes" 6 70
            exit 1
	elif [ ! -d $MTPT/boot ]; then
	    /bin/dialog --title "Error: no /boot found" --msgbox "$no_boot_mes" 6 70
            exit 1
	elif [ ! -L $MTPT/boot/vmlinuz ] ; then
	    /bin/dialog --title "Error: no /boot/vmlinuz found" --msgbox \
		"$no_vmlinuz_mes" 6 70
	    exit 1
	fi

	ROOT_DEVICE=`mount -v | grep "$MTPT " | cut -f1 -d' '`
	mount --bind /proc $MTPT/proc
	mount --bind /sys $MTPT/sys
	mount --bind /dev $MTPT/dev
    fi
fi

echo "$ROOT_DEVICE" > $MTPT/tmp/grub_ROOT_DEVICE

expand_mes
/bin/dialog --title "exec grub-install" --yesno "$exec_mes" 10 70

if [ $? -ne 0 ]; then
	/bin/dialog --title "User exit" --msgbox "$exit_mes" 6 70
	exit 1
fi

ROOT_DISK=`echo $ROOT_DEVICE | sed "s/[0-9]$//" | sed "s/[0-9p]$//"`
gpt_test=`LANG=C ; fdisk -l $ROOT_DISK | grep Disklabel | grep gpt`

if [ "$gpt_test.x" != ".x" ]; then   # GPT partition
    efivars_chk=`cat /proc/mounts | grep efivarfs`
    if [ "$efivars_chk.x" = ".x" ]; then
	mount -t efivarfs efivarfs /sys/firmware/efi/efivars
	mount --bind /sys/firmware/efi/efivars $MTPT/sys/firmware/efi/efivars
    fi
    echo $ROOT_DISK > $MTPT/tmp/grub_ROOT_DISK
    if [ -f /tmp/ESP_partintion ]; then
        cat /tmp/ESP_partition > $MTPT/tmp/ESP_partition
    fi
    chroot $MTPT /sbin/grubconfig_efi
else    
    chroot $MTPT /sbin/grubconfig_mbr
fi    
