#!/bin/sh
#
# joystick initscript
#
### BEGIN INIT INFO
# Provides:          joystick
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Store and restore joystick calibration
# Description:       This script restores joystick calibration on
#                    shutdown and restores it on bootup.
### END INIT INFO

# Don't use set -e; check exit status instead

# Exit silently if package is no longer installed
[ -x /usr/bin/jscal ] || exit 0

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

. /lib/lsb/init-functions

case "$1" in
  start)
	log_daemon_msg "Restoring joystick calibration"
	if [ ! -c /dev/input/js0 ]; then
	  log_progress_msg "no joysticks available"
	  log_end_msg 0
	  exit 0
	fi
	if [ ! -f /var/lib/joystick/joystick.state ]; then
	  log_progress_msg "no calibration data"
	  log_end_msg 0
	  exit 0
	fi
	for js in /dev/input/js*; do
	  settings=$(grep $js /var/lib/joystick/joystick.state)
	  if [ ! -z "$settings" ]; then
	    settings=$(echo $settings | cut -d' ' -f3)
	    jscal -s $settings $js
	    log_progress_msg $(basename $js)
	  fi
	done
	log_end_msg 0
	exit 0
	;;
  stop)
	log_daemon_msg "Storing joystick calibration"
	if [ ! -c /dev/input/js0 ]; then
	  log_progress_msg "no joysticks available"
	  log_end_msg 0
	  exit 0
	fi
	if [ ! -d /var/lib/joystick ]; then mkdir -p /var/lib/joystick; fi
	> /var/lib/joystick/joystick.state
	for js in /dev/input/js*; do
	  jscal -p $js >> /var/lib/joystick/joystick.state
	  log_progress_msg $(basename $js)
	done
	log_end_msg 0
	exit 0
	;;
  restart|force-reload)
	EXITSTATUS=0
	$0 stop || EXITSTATUS=1
	$0 start || EXITSTATUS=1
	exit $EXITSTATUS
	;;
  *)
	echo "Usage: $0 {start|stop|restart}" >&2
	exit 3
	;;
esac

