#!/bin/bash
# --- ROCK-COPYRIGHT-NOTE-BEGIN ---
# 
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# Please add additional copyright information _after_ the line containing
# the ROCK-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
# the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
# 
# ROCK Linux: rock-src/package/base/sysfiles/stone_mod_joystick.sh
# ROCK Linux is Copyright (C) 1998 - 2006 Clifford Wolf
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. A copy of the GNU General Public
# License can be found at Documentation/COPYING.
# 
# Many people helped and are helping developing ROCK Linux. Please
# have a look at http://www.rocklinux.org/ and the Documentation/TEAM
# file for details.
# 
# --- ROCK-COPYRIGHT-NOTE-END ---
#
# [MAIN] 80 joystick Joystick Configuration

#jstest output
#Driver version is 2.1.0.
#Joystick (LogiCad3D Magellan / SpaceMouse) has 6 axes (X, Y, Z, Rx, Ry, Rz)
#and 9 buttons (Btn0, Btn1, Btn2, Btn3, Btn4, Btn5, Btn6, Btn7, Btn8).

add_js() { #{{{
	unset cmd
	while read long short desc ; do
		cmd="${cmd} '${desc}' 'driver=\"${long}\"'"
	done < <( inputattach --help | grep -- -- )
	eval "gui_menu add_js 'Add new joystick' ${cmd}"
	[ -z "${driver}" ] && return
	gui_input "Enter device to attach ${desc} to" "/dev/tts/0" device
	[ -z "${device}" ] && return
	if grep -q "joystick ${driver} ${device}" /etc/conf/joystick ; then
		gui_message "This device is already configured!"
		return
	fi
	inputattach ${driver} ${device} &
	sleep 1
	for x in /dev/input/js* ; do : ; done
	jscal -c ${x}
	read command parameter setting dev < <( jscal -p ${x} )
	echo "joystick ${driver} ${device} ${setting}" >> /etc/conf/joystick
} #}}}
edit_js() {
	driver="${1}" ; shift
	device="${1}" ; shift
	setting="${1}" ; shift
	name="${@}"
	gui_menu edit_js "Edit ${name} on ${device}" "Change device ${device}" "gui_input 'Enter new device name' '${device}' device" \
		"Recalibrate this joystick" "sed -e 's=^joystick ${driver} ${device} ${setting}=joystick ${driver} ${device} recalibrate=g' -i /etc/conf/joystick ; rc joystick restart"
}
main() {
	[ -e /etc/conf/joystick ] || touch /etc/conf/joystick
	tmp="$( mktemp )"
	inputattach --help > ${tmp}
	while
		unset cmd
		while read type driver device setting ; do
			[ "${type}" == "joystick" ] || continue
			read long short name < <( grep -- ${driver} ${tmp} )
			if [ -z "${name}" ] ; then
				gui_message "Unknown driver \"${long}\" on device \"${device}\"!"
			fi
			cmd="${cmd} 'Edit ${name} on ${device}' 'edit_js ${driver} ${device} ${setting} ${name}'"
		done < /etc/conf/joystick
		eval "gui_menu joystick 'Joystick settings' 'Add new joystick' 'add_js' 'Configured joysticks' '' ${cmd}"
	do :
	done
}
