BASE=/sys/class/sound

strip () {
	cardid=${1#$BASE/card}
	echo ${cardid%/id}
}

if lsmod | grep -q speakup_soft; then
	# Give drivers some time to detect boards :/
	sleep 2
	IDS=$(echo $BASE/card*/id)
	N=$(echo $IDS | wc -w)
	case $N in
		0)
			echo No sound card detected, can not do software speech synthesis... Press enter to continue anyway.
			read
			;;
		1)
			# Just one card, can not be wrong
			echo $(strip $IDS) > /var/run/espeakup.card
			/usr/bin/espeakup -V en > /var/log/espeakup.log 2>&1
			;;
		*)
			# Several cards, make the user choose
			CARD=none
			while [ "$CARD" = none ]
			do
				for ID in $IDS
				do
					i=$(strip $ID)
					ALSA_CARD=$(cat /sys/class/sound/card$i/id) /usr/bin/espeakup -V en >> /var/log/espeakup.log 2>&1
					while ! [ -r /var/run/espeakup.pid ]
					do
						sleep 0.1
					done
					pid=$(cat /var/run/espeakup.pid)
					answer=none
					echo Please type enter to use this sound board
					read -t 5 answer
					kill $pid
					while [ -r /var/run/espeakup.pid ]
					do
						sleep 0.1
					done
					if [ "$answer" != none ]
					then
						CARD=$i
						break
					fi
				done
			done
			echo "$CARD" > /var/run/espeakup.card
			ALSA_CARD=$(cat /sys/class/sound/card$CARD/id) /usr/bin/espeakup -V en >> /var/log/espeakup.log 2>&1
	esac
fi
