#!/bin/ash
# $1 quiet mode indicator - ex: q
#this is called from 'init', runs as parallel process.
#170525 usb stuff rewritten with no dmesg stuff

#wait for usb partitions to become available...
#entries in /sys/block show up, but ex /sys/block/sda/sda1 takes a bit longer...
#note, if usb card-reader plugged in but no cards inserted, this will timeout...
#note, will also timeout if usb optical drive (sr), but ok, they need extra time...

[ "$KERNELVER" = "" ] && KERNELVER="$(uname -r)"

# Put some reasonable numbers here.. this logic can be revised..
case $KERNELVER in
	3.*) TIMEOUT=5 ;;
	*)  TIMEOUT=4 ;;
esac

echo "[WAIT4USB] TIMEOUT=${TIMEOUT}" #debug

CNTUSB=0
USBDRVS="$(find /sys/block -maxdepth 1 -name 'sd*' -o -name 'sr*' | xargs -n 1 readlink 2>/dev/null | grep '/usb[0-9]')"
while [ "$USBDRVS" = "" ]; do
	[ $CNTUSB -ge $TIMEOUT ] && break
	sleep 1
	[ "${1}" ] || echo -en "\\033[1;33m.\\033[0;39m" >/dev/console #yellow dot
	USBDRVS="$(find /sys/block -maxdepth 1 -name 'sd*' -o -name 'sr*' | xargs -n 1 readlink 2>/dev/null | grep '/usb[0-9]')"
	CNTUSB=$(($CNTUSB + 1))
	echo -n " - $CNTUSB" #debug
done
echo

for ONEDRV in $USBDRVS; do
	ONEDRV=${ONEDRV##*/}
	ALLUSBDRVS="${ALLUSBDRVS}${ONEDRV} "
	CNTUSB=0
	while [ ! -e /sys/block/${ONEDRV}/${ONEDRV}1 ]; do
		sleep 1
		[ "${1}" ] || echo -en "\\033[1;31m.\\033[0;39m" >/dev/console #red dot
		CNTUSB=$(($CNTUSB + 1))
		[ $CNTUSB -gt 1 ] && break
	done
done

echo -n "${ALLUSBDRVS% }" > /tmp/flag-usb-ready

### END ###
