#!/bin/sh
#if woof builds 'initrd' inside 'vmlinuz', then 'BOOT_SPECS' will not be inside 'initrd'.
#190714 support nvme drives.
#190716 no longer have guess_fstype
#20210526 allow ntfs. optional: pass in name of file to look for, BOOT_UUID, BOOT_DIR
#20210611 paragon ntfs driver needs "-t ntfs3" mount option.

#if initrd has 'EASY_ID' use that...
EASYID=""
[ -f /EASY_ID ] && EASYID="-$(cat /EASY_ID)"
BSFILE="BOOT_SPECS${EASYID}" #20210526 historical support.

if [ "$1" ];then #20210526
 BSFILE="$1"
fi

echo -e "\\033[1;31mSearching for external ${BSFILE} file\\033[0;39m" #red.

mkdir -p /mntpt
CNT=1
echo -n "" > /checked

XPART=''; MMPARTS=''; SDPARTS=''; NVPARTS=''
while [ $CNT -lt 5 ];do
 sleep 2
 
 if [ "$2" ];then #20210526
  XPART="$(blkid | grep "${2}" | cut -f 1 -d ':' | cut -f 3 -d '/' | head -n 1)"
 else
  #MMPARTS="$(grep -o 'mmcblk[0-9]p[0-9]' /proc/partitions)"
  #SDPARTS="$(grep -oE 'sd[a-z][0-9]+' /proc/partitions)"
  MMPARTS="$(ls -1d /sys/block/mmcblk[0-9]/mmcblk[0-9]p[0-9] 2>/dev/null | rev | cut -f 1 -d '/' | rev | tr '\n' ' ')"
  SDPARTS="$(ls -1d /sys/block/sd[a-z]/sd[a-z][0-9]* 2>/dev/null | rev | cut -f 1 -d '/' | rev | tr '\n' ' ')"
  #NVMe drives have device nodes in /dev of the form "nvme[0-9]n[1-9]". Partitions are appended as "p<number>", for example "nvme0n1p3".
  NVPARTS="$(ls -1d /sys/block/nvme[0-9]n[1-9]/nvme[0-9]n[1-9]p[0-9]* 2>/dev/null | rev | cut -f 1 -d '/' | rev | tr '\n' ' ')"
 fi
 
 for aPART in ${MMPARTS} ${SDPARTS} ${NVPARTS} ${XPART}
 do
  [ "$aPART" == "" ] && continue
  if grep -w "$aPART" /checked >/dev/null;then continue; fi
  echo "$aPART" >> /checked
  #aFS="$(guess_fstype /dev/${aPART} | grep -E 'ext|vfat|f2fs')"
  aFS="$(blkid /dev/${aPART} | grep -E 'ext|vfat|f2fs|ntfs' | tr ' ' '\n' | grep '^TYPE=' | cut -f 2 -d '"')" #190716 20210526
  [ "$aFS" == "" ] && continue
  if grep -q 'ntfs3' /proc/filesystems;then #20210611 has paragon ntfs3 driver.
   mount -t ${aFS/ntfs/ntfs3} /dev/${aPART} /mntpt
  else
   mount -t ${aFS} /dev/${aPART} /mntpt
  fi
  if [ $? -eq 0 ];then
   if [ "$3" ];then #20210526 BOOT_DIR
    if [ -f /mntpt/${3}${BSFILE} ];then
     BSF="/mntpt/${3}${BSFILE}"
    fi
   else
   BSF="$(ls -1 /mntpt/${BSFILE} 2>/dev/null | head -n 1)"
   [ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/${BSFILE} 2>/dev/null | head -n 1)"
   [ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/*/${BSFILE} 2>/dev/null | head -n 1)"
   #[ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/*/*/${BSFILE} 2>/dev/null | head -n 1)"
   fi
   if [ "$BSF" ];then
    cp -f ${BSF} /BOOT_SPECS
    sync
   fi
   umount /mntpt
   [ -f /BOOT_SPECS ] && break
  fi
 done
 [ -f /BOOT_SPECS ] && break
 CNT=$(($CNT+1))
done

###end###
