#!/bin/sh
#
# Start Mouse event server

PIDFILE=/var/run/gpm.pid
GPM=/usr/sbin/gpm
CFG=/etc/gpm.conf

test -x $GPM || exit 0

if [ "$(id -u)" != "0" ]
then
  echo "You must be root to start, stop or restart gpm."
  exit 1
fi

cmdln=
niceness=0

if [ -f $CFG ]; then
  . $CFG
  if [ -n "$device" ]; then cmdln="$cmdln -m $device"; fi
  if [ -n "$type" ]; then cmdln="$cmdln -t $type"; fi
  if [ -n "$responsiveness" ]; then cmdln="$cmdln -r $responsiveness"; fi
  if [ -n "$sample_rate" ]; then cmdln="$cmdln -s $sample_rate"; fi
  # Yes, this /IS/ correct! There is no space after -R!!!!!!
  # I reserve the right to throw manpages at anyone who disagrees.
  if [ -n "$repeat_type" ] && [ "$repeat_type" != "none" ]; then
    cmdln="$cmdln -R$repeat_type"
  fi
  if [ -n "$append" ]; then cmdln="$cmdln $append"; fi
  # If both the second device and type are specified, use it.
  if [ -n "$device2" ] && [ -n "$type2" ] ; then
    cmdln="$cmdln -M -m $device2 -t $type2"
  fi
fi

gpm_strace () {
  echo -n "Running mouse interface server under strace: gpm"
  eval strace -T -o /root/gpm.strace $GPM -V -D -e $cmdln > /root/gpm.out 2>&1
  echo "."
  return 0
}

gpm_start () {
  echo -n "Starting mouse interface server: gpm"
  eval start-stop-daemon --start --quiet --nicelevel $niceness --exec $GPM \
    -- $cmdln || { echo " start failed."; return 1; }
  echo "."
  return 0
}

gpm_stop () {
  echo -n "Stopping mouse interface server: gpm"
  $GPM -k || { echo " not running."; return 1; }
  echo "."
}


case "$1" in
  strace)
     gpm_strace || exit 1
     ;;
  start)
     gpm_start || exit 1
     ;;
  stop)
     gpm_stop || exit 1
     ;;
  force-reload|restart)
     gpm_stop && sleep 3
     gpm_start || exit 1
     ;;
  *)
     echo "Usage: /etc/init.d/gpm {start|stop|restart|force-reload|strace}"
     exit 1
esac

exit 0
