#!/bin/bash
set -e
diskName=$1

if [ "x$diskName" = "x" ]; then
	echo "传入分区名为空"
fi

efibootdir=`ls -a /sys/firmware/efi/efivars`

mountrootdir=/home/kylin/fixBootDir

if [ ! -d "$mountrootdir" ]; then
        mkdir -p $mountrootdir
fi

parse_device(){
        device=$1
        if echo $device | grep -E -q "^UUID="; then
                echo $device | sed 's:^UUID=:/dev/disk/by-uuid/:' | tr -d "\n"
        elif echo $device | grep -E -q "^LABEL="; then
                echo $device | sed 's:^LABEL=:/dev/disk/by-label/:' | tr -d "\n"
        else
                echo $device | tr -d "\n"
        fi
}

mount $diskName $mountrootdir
mount --bind /dev "$mountrootdir/dev"
mount --bind /dev/pts "$mountrootdir/dev/pts"
mount --bind /proc "$mountrootdir/proc"
mount --bind /sys "$mountrootdir/sys"
if [ ! -z efibootdir ]; then
	mount --bind /sys/firmware/efi/efivars "$mountrootdir/sys/firmware/efi/efivars"
fi
cat "$mountrootdir/etc/fstab" | grep -Ev "^#" | grep -Ev "^$" | awk '{print $1 " " $2 " " $3 " " $4 " " $5 " " $6}' |
while read device mntdir fstype options dump passno ;
do
	if [ "x$mntdir" = "x/" ] ; then
		echo "mount 挂载点为根目录，不需要挂载"
		continue
	fi
	if [ "x$mntdir" = "xnone" ] ; then
		echo "mount 为swap分区，不需要挂载"
		continue
	fi
        if [ "x$device" = "x/data/home" ] || [ "x$device" = "x/data/root" ] ; then
            echo "mount data分区home root目录，不需要挂载"
            continue
        fi
	echo "$device $options"
	device=$(parse_device $device)
	echo "$device, -------------- $mntdir"
	echo "mount -n -o $options $mountrootdir$device $mountrootdir$mntdir"
	mount -n -o $options $device $mountrootdir$mntdir

        if cat /proc/cpuinfo|grep -i "kirin.*9.0" > /dev/null || cat /proc/cpuinfo|grep -i "pangu.*m900" > /dev/null ;then
            if [ "x$mntdir" = "x/boot/efi" ] || [ "x$mntdir" = "x/boot" ] ; then
                mount -o rw,remount $device $mountrootdir$mntdir
            fi
        fi
done

cp /usr/share/kylin-fix-boot-grub/fix-bash/fix-grub-real "$mountrootdir/fix-grub-real"
chroot $mountrootdir /fix-grub-real >> /var/log/kylin-fix-boot-grub/fix-grub.log 2>&1
umount -l $mountrootdir

