if [ $# -eq 1 ] && [[ $1 =~ ^nvme[]0-9]n[]0-9] ]]; then     #with one arg as nvme*n*

mountpoint -q /mnt/boot/efi 
if [ $? -eq 0 ]; then     #is a mount point
 echo "umount /mnt/boot/efi existing mountpoint"
 echo '12' | sudo -S umount /mnt/boot/efi
fi
mountpoint -q /mnt
if [ $? -eq 0 ]; then
 echo "umount /mnt existing mountpoint"
 echo '12' | sudo -S umount /mnt
fi

 echo -n "parted mklabel gpt..."
 echo '12' | sudo -S parted -s /dev/nvme0n1 mklabel gpt 
 echo "done"
 
 echo -n "crate EFI partion ..."
sudo parted -s /dev/nvme0n1 mkpart  'EFI' 'fat32' 1MiB 500MiB
 echo "done"
 
 echo -n "formate EFI partion as FAT32 with given VOLUME ID..."
sudo mkfs.fat -i 2A9295E4 -F 32 /dev/nvme0n1p1
 echo "done"

 echo -n "crate OS partion ..."
sudo parted -s /dev/nvme0n1 mkpart  'OS' 'ext4' 500MiB 100%
 echo "done"

 echo -n "formate OS partion as ext4 with given UUID..."
sudo mkfs.ext4 -q -F -U '0296c5ca-bdb7-4676-9c6b-363b727e36b4' /dev/nvme0n1p2
 echo "done"


  echo -n "mount partions..."
sudo mount /dev/nvme0n1p2 /mnt/
sudo mkdir /mnt/boot && sudo mkdir /mnt/boot/efi
sudo mount /dev/nvme0n1p1 /mnt/boot/efi
 echo "done"

  echo -n "extract OS backup, this may take a few minutes ... "
sudo tar xpf  ~/backup2.tar  -C /mnt
sudo chown -R "$(whoami)" /mnt/home/"$(whoami)"     #need change ownership of user home directory
sudo cp ~/OS/fstab /mnt/etc/fstab                   #need config fstab for auto mount

 echo "done"

  echo -n "chroot and update grub ... "

if [ ! -d "/mnt/dev/pts" ]; then
 sudo mkdir /mnt/dev/pts
 fi
for i in dev dev/pts proc sys run; do sudo mount -o bind /$i /mnt/$i; done
sudo chroot /mnt /bin/bash <<"EOT"
update-grub2      ###change root 后此命令将在/boot/grub/目录下生成grub.cfg文件
exit
EOT

for i in dev dev/pts proc sys run; do sudo umount /mnt/$i; done
 echo "done"
 
  echo -n "install grub ... "
sudo grub-install --boot-directory=/mnt/boot /dev/nvme0n1    
 echo "done"
 
sudo efibootmgr -c -d /dev/nvme0n1 -p 1 -L "new_OS" -l '\efi\ubuntu\shimx64.efi' 
 efibootmgr -v

 shutdown -r now

else
  echo -n "invalid parameter, expect nvmeXnX "
 
fi
  

