#!/bin/bash

[ "x$1" = "xprereqs" ] && exit

[ "x$debug" = "xy" ] && set -x

probe_hdd() {
  entry="nosuchdevice"

  blkid > /dev/null # a mini sleep
  for line in `ls /sys/block/ | grep -e "^sd" -e "^hd" -e "^mmcblk" -e "^xvd" -e "^nvme"`; do
    if ( echo $line | grep -q "$entry" ); then
      #skip
      echo > /dev/null
    else
      entry=$line
      echo "/dev/$entry"
    fi
  done
}

probe_bootpart() {
  [ "x$MODE" = "xpxe" ] && return

  # bootpart is where ukit-$MODE.ver is
  # address the issue: ukit will see two ukit.ver files when it is being used to capture the thinpropc image 
  # this is still not idea but much better than share the same file name across different types of ukit operations
  rm -rf /tmp/tmpmnt
  mkdir -p /tmp/tmpmnt
  for p in `blkid | sed "s/:.*//"`; do
    mount -o ro $p /tmp/tmpmnt 2>/dev/null
    [ -e /tmp/tmpmnt/ukit-$MODE.ver ] && bootpart=$p
    umount /tmp/tmpmnt 2>/dev/null
    [ "x$bootpart" != "x" ] && break
  done
}

probe_bootdisk() {
  [ "x$MODE" = "xpxe" ] && return

  # bootdisk is where bootpart is
  for d in $hddlist; do
    echo $bootpart | grep -o $d && bootdisk=$d
    [ "x$bootdisk" != "x" ] && break
  done;
}

probe_sysdisk() {
  if [[ "x$MODE" = "xprism" || "x$MODE" = "xtpcmd" ]]; then
    sysdisk=$bootdisk
    return
  fi

  lines=`echo "$hddlist" | wc -l `
  if [ $lines = 1 ] ; then
    # sysdisk is the only disk on the system
    sysdisk=$hddlist
  elif [ "x$bootdisk" != "x" ]; then
    # or first disk after bootdisk is removed from the list
    sysdisk=`echo "$hddlist" | grep -v $bootdisk | head -1`
  else
    # pxe boot case, we don't have a boot disk, so use first disk as sysdisk
    sysdisk=`echo "$hddlist" | head -1`
  fi
}

probe_prismpart() {
  [ "x$MODE" != "xprism" ] && return

  # prismpart is where image.ini is
  rm -rf /tmp/tmpmnt
  mkdir -p /tmp/tmpmnt
  for p in `blkid | sed "s/:.*//"`; do
    mount -o ro $p /tmp/tmpmnt 2>/dev/null
    [ -e /tmp/tmpmnt/image.ini ] && prismpart=$p
    umount /tmp/tmpmnt 2>/dev/null
    [ "x$prismpart" != "x" ] && break
  done
}

i=0
while [ $i -lt 20 ]; do
  hddlist=`probe_hdd`;
  #echo $i : $hddlist;
  if [ "x$hddlist" != "x$oldhddlist" ]; then
    i=0
    oldhddlist=$hddlist
  else
    i=$((i+1))
    sleep 0.1
  fi
done

[ "x$bootpart" = "x" ] && probe_bootpart
[ "x$bootdisk" = "x" ] && probe_bootdisk
[ "x$sysdisk" = "x" ] && probe_sysdisk
[ "x$prismpart" = "x" ] && probe_prismpart

echo "BOOTDISK=${bootdisk:-none}" >> /conf/param.conf
echo "BOOTPART=${bootpart:-none}" >> /conf/param.conf
echo "SYSDISK=${sysdisk:-none}" >> /conf/param.conf
echo "PRISMPART=${prismpart:-none}" >> /conf/param.conf

