#!/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

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

#if initrd has 'EASY_ID' use that...
EASYID=""
[ -f /EASY_ID ] && EASYID="-$(cat /EASY_ID)"

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

while [ $CNT -lt 5 ];do
 sleep 2
 #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' ' ')"
 
 for aPART in ${MMPARTS} ${SDPARTS} ${NVPARTS}
 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' | tr ' ' '\n' | grep '^TYPE=' | cut -f 2 -d '"')" #190716
  [ "$aFS" == "" ] && continue
  mount -t ${aFS} /dev/${aPART} /mntpt
  if [ $? -eq 0 ];then
   BSF="$(ls -1 /mntpt/BOOT_SPECS${EASYID} 2>/dev/null | head -n 1)"
   [ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/BOOT_SPECS${EASYID} 2>/dev/null | head -n 1)"
   [ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/*/BOOT_SPECS${EASYID} 2>/dev/null | head -n 1)"
   #[ "$BSF" == "" ] && BSF="$(ls -1 /mntpt/*/*/*/BOOT_SPECS${EASYID} 2>/dev/null | head -n 1)"
   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###
