#!/bin/bash

# This script was written by Nick Wilbanks
# and is released under the GPL v2
# it was inspired by wiimote_connect.rb
# written by Heavybell.
# Some things aren't done properly
# so use at your own risk!

# requires kdialog to function properly

declare -a myConfigFiles
declare -a configList
declare -a hctscan
declare -a wiimote

echo "started on `date`" >> /tmp/wiimote_watch.log

# directory to look for config files in.
cd ~/.cwiid/wminput/

# add all files in the directory above to an array
for file in *
do
	myConfigFiles[${#myConfigFiles[@]}]="$file"
done

# do some ugly stuff so kdialog behaves how we want
for ((  i=0 ;  i <= ${#myConfigFiles[@]} * 2 - 2; i++  ))
do
	configList[i*2+1]=${myConfigFiles[i]}
	configList[i*2]=${myConfigFiles[i]}
done

# main loop
# look for a wiimote. When one is found, ask the user which config file to use then start wminput
while true
do
	hctscn=`/usr/bin/hcitool scan | grep Nintendo`
        if [ "`echo ${hctscn[@]}`" ]; then
		# parse  the output output of hcitool scan
		n=0
		for i in `echo ${hctscn} | tr '.' '\n'` ; do
			str=${str},${i}
			let n=$n+1
			wiimote[${n}]=${i}
		done
		kdialog --passivepopup "Wiimote Found at ${wiimote[1]}." 5 &
		whichConfig=`kdialog --menu "Select Which config file to use:" ${configList[@]}`
		echo "Starting wminput for wiimote with blutooth address ${wiimote[1]} and configuration file $whichConfig" >> /tmp/wiimote_watch.log
		wminstatus="`/usr/local/bin/wminput -c $whichConfig ${wiimote[1]}`"
		echo "Wiimote disconnected." >> /tmp/wiimote_watch.log
                kdialog --passivepopup "Wiimote was Disconnected." 5 &
        fi
	# My system acts up if I don't pause 
	# before doing an hcitool scan continually
	# you might not need this. Comment it out if you don't.
	sleep 10
done

exit 0

