#!/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
# (unless you specify a config on the commandline
# and use the -b barebones flag)

# Modified by Nick Sabalausky:
# - Allow a config file to be specified
#   on the command line.
# - Added -b barebones flag to disable kde-based
#   menu and notifications (only allowed when
#   a config file is specified on the commandline).

configParam=$1
optionParam=$2

kdeOffStr="-b" #"barebones"

if [ "$optionParam" != "" -a "$optionParam" != "$kdeOffStr" -o "$configParam" = "--help" -o "$configParam" = "$kdeOffStr" ]; then
	echo ""
	echo "Wiimote Watch Script"
	echo ""
	echo "Usage:"
	echo "  ./wiimote_watch.sh [[config] -b]"
	echo ""
	echo "config: Name of config file to use. If omitted,"
	echo "        a KDE-based menu will the allow user to"
	echo "        select a config whenever a wiimote is detected."
	echo ""
	echo "-b:     Barebones. If config is specified, disables all"
	echo "        KDE-based gui elements."
	echo ""
	exit 0
fi

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

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

if [ "$optionParam" != "$kdeOffStr" ]; then
	# directory to look for config files in.
	cd /usr/local/etc/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
fi

# 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

		if [ "$optionParam" != "$kdeOffStr" ]; then
			kdialog --passivepopup "Wiimote Found at ${wiimote[1]}." 5 &
		fi

		if [ "$configParam" = "" ]; then
			whichConfig=`kdialog --menu "Select Which config file to use:" ${configList[@]}`
		else
			whichConfig=$configParam
		fi
		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]}`"

		if [ "$optionParam" != "$kdeOffStr" ]; then
			echo "Wiimote disconnected." >> /tmp/wiimote_watch.log
	                kdialog --passivepopup "Wiimote was Disconnected." 5 &
        fi
	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

