#!/bin/ash
#101121 --modcheck=<module> call is in rerwin's firmware scripts.
#121003 rerwin: rewritten to wait for loading delays & accept --modcheck wildcard (e.g., hsf*).

PARAM1="$1"

write_delay_log() {
 echo "$(date +%H:%M:%S.%N | cut -c 1-12) ${$} $MODULE - $1" >> /tmp/pup_event_backend/delay.log
}

case $PARAM1 in
 --modcheck*)
  MODULE="$(echo "$PARAM1" | cut -f 2 -d '=')"
  if [ "$(echo $MODULE | grep '\*')" ];then
   MODBASE="$(echo $MODULE | grep -o '^[^\*]*')"
   MODULE="$(cat /tmp/pup_event_backend/protect1-* | grep -w -o -s "${MODBASE}[^ ]*" | tail -n 1)"
   [ "${MODULE}" ] || exit 1
  fi
  lsmod | grep -q -s "^${MODULE} " && exit 0
  [ "$(grep -s " ${MODULE} " /tmp/pup_event_backend/protect1-*)" = "" ] \
   && [ "$(grep '^ADDLIST=' /etc/rc.d/MODULESCONFIG | grep " ${MODULE} ")" = "" ] \
   && exit 1
  write_delay_log "Began wait for loading"
  FIRMWARE="$(grep -w "${MODULE}.ko" /etc/modules/firmware.dep.$(uname -r)| grep '^[^:]*')"
  BRKCNT=0; STATUS=1; MODPATH=""
  while [ $BRKCNT -lt 10 ];do
   if [ "$FIRMWARE" ] && [ -f /pinstall.${FIRMWARE}.sh ];then
    sleep 1
   else #any pinstall completed
    if [ "$MODPATH" = "" ];then
     MODPATH="$(find /lib/modules/$(uname -r)/ -maxdepth 6 -type f -name ${MODULE}.ko)"
     if [ "$MODPATH" = "" ];then
      write_delay_log "Not installed"
      STATUS=2; break
     fi
    else #module installed
     sleep 1
     if lsmod | grep -q -s "^${MODULE} ";then
      write_delay_log "Ended wait for loading"
      STATUS=0; break
     fi
    fi
   fi
   BRKCNT=$(($BRKCNT + 1))
  done
  [ $STATUS -eq 1 ] && write_delay_log "Wait for loading exceeded timeout limit"
  exit $STATUS
 ;;
esac

exit 0
###END###
