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 :/
	echo "Starting speech synthesis, please wait while we probe your sound card(s)..."
	sleep 1
	S=1
	while true
	do
		IDS=$(echo $BASE/card*/id)
		if [ "$IDS" = "$BASE/card*/id" ]; then
			if [ "$S" -ge 3 ]; then
				echo "No sound card detected after $S seconds..."
			fi
			if [ "$S" -lt 80 ]; then
				# We have seen cards taking as much as 12s to get initialized...
				sleep 1
				S=$((S+1))
				continue
			else
				echo "Can not do software speech synthesis... Press enter to continue anyway."
				read
				break
			fi
		fi

		IDS=$(echo $BASE/card*/id)
		N=$(echo $IDS | wc -w)

		# Sleep again as much, in case more cards are to come :/
		echo "Found $N audio card(s), waiting for $S more seconds for any other card..."
		sleep $S

		. /usr/share/alsa/utils.sh
		preinit_levels all > /dev/null 2>&1
		sanify_levels all > /dev/null 2>&1

		IDS=$(echo $BASE/card*/id)
		N=$(echo $IDS | wc -w)

		echo "Found $N audio card(s)."

		case $N in
		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 --alsa-volume -V en >> /var/log/espeakup.log 2>&1
					while ! [ -r /var/run/espeakup.pid ]
					do
						sleep 1
					done
					pid=$(cat /var/run/espeakup.pid)
					answer=none
					echo "Please type enter to use this sound board (number $i)"
					read -t 5 answer
					kill $pid
					while [ -r /var/run/espeakup.pid ]
					do
						sleep 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 --alsa-volume -V en >> /var/log/espeakup.log 2>&1
		esac

		break
	done
fi
