#!/bin/bash

source /etc/tos/scripts/scripts

#/dev/sda,/dev/sdb,...
blk=$1
if [ ! -b "$blk" ]; then
    echo "invalid block device" >&2
    exit 1
fi

N5_UEFI=$(awk '/model name/' /proc/cpuinfo |uniq|egrep "N[45]")
#grub-install
mkdir -p /mnt/bootparts
if [ ! -z "$N5_UEFI" ]; then
#    echo -e "y\n" | /sbin/mke2fs -t vfat ${blk}1
    mkfs.vfat -n $TOS_DISK_SIGN ${blk}1
    fatlabel ${blk}1 $TOS_DISK_SIGN
else
    echo -e "y\n" | mke2fs -t ext4 ${blk}1
    e2label ${blk}1 $TOS_DISK_SIGN
fi

mount ${blk}1 /mnt/bootparts
df-json | grep /mnt/bootparts >/dev/null
if [ $? -ne 0 ]; then
    echo "mount ${blk}1 /mnt/bootparts failed" >&2
    exit 2
fi
if [ ! -z "$N5_UEFI" ]; then
    /sbin/grub-install --target=x86_64-efi --efi-directory=/mnt/bootparts/ --boot-directory=/mnt/bootparts/boot --bootloader-id=boot $blk --force
    cp -rf /EFI /mnt/bootparts/
    cp -rf /boot /mnt/bootparts/
else
    /sbin/grub-install --root-directory=/mnt/bootparts/ $blk --force
    wait $!
    cp /boot/grub/grub.cfg /mnt/bootparts/boot/grub/ -a
    if [ -e /boot/grub/bzImage ]; then
        cp -a /boot/grub/bzImage /mnt/bootparts/boot/
    else
        cp -a /boot/bzImage /mnt/bootparts/boot/
    fi
    [ -e /boot/.tosloader ] && cp -a /boot/.tosloader /mnt/bootparts/boot/
fi

sync
umount /mnt/bootparts
exit 0
