#!/bin/bash

# sixad-bin wrapper
# written by falkTX

DEBUG=0
LEGACY=0

. /etc/default/sixad

if [ -f /usr/bin/sudo ]; then
  SUDO="/usr/bin/sudo"
else
  SUDO=""
fi

bt_device_check () {
if (which hciconfig > /dev/null); then
  if (hciconfig dev > /dev/null); then
    VER=`hciconfig default version | grep "HCI Ver" | awk '{print$3}'`
    if [ "$VER" == "1.1" ]; then
      echo "***** NOTICE *****"
      echo "You're using a very old bluetooth dongle,"
      echo "the Sixaxis will not work properly!"
    elif [ "$VER" == "1.0" ]; then
      echo "***** WARNING *****"
      echo "You're using a _really_ old bluetooth dongle,"
      echo "the Sixaxis will just not work!"
    fi
  else
    echo "No bluetooth adapters found on the system!"
    echo "sixad will now quit"
    exit
  fi
fi
}

sixad_running_check () {
ps -e | grep sixad-bin > /dev/null
}

bluetoothd_running_check () {
ps -e | grep bluetoothd > /dev/null
}

modprobe_check () {
$SUDO /sbin/modprobe uinput
}

bt_start () {
if [ -f /etc/rc.d/rc.bluetooth ]; then
  $SUDO /etc/rc.d/rc.bluetooth start
else
  $SUDO /etc/init.d/bluetooth start
fi
}

bt_stop() {
if (bluetoothd_running_check); then
  if [ -f /etc/rc.d/rc.bluetooth ]; then
    $SUDO /etc/rc.d/rc.bluetooth stop
  else
    $SUDO /etc/init.d/bluetooth stop
  fi
fi
}

case $1 in

  --start|-start|start|-s)
REMOTE=0
bt_device_check
if (sixad_running_check); then
  echo "sixad is already running."
  echo "run '$0 --stop' to stop it"
else
 if (modprobe_check); then  #Check for root access before running, If NO access, quit
  bt_stop
  $SUDO /usr/sbin/sixad-bin $DEBUG $LEGACY $REMOTE
 else
  echo "You need admin/root access to run this application"
 fi
fi
  ;;

  --stop|-stop|stop)
$SUDO pkill -KILL sixad-sixaxis
$SUDO pkill -KILL sixad-remote
$SUDO pkill -TERM sixad-bin
bt_start
  ;;

  --remote|-remote|remote)
REMOTE=1
bt_device_check
if (modprobe_check); then  #Check for root access before running, If NO access, quit
  bt_stop
  $SUDO /usr/sbin/sixad-bin $DEBUG $LEGACY $REMOTE
else
  echo "You need admin/root access to run this application"
fi
  ;;

  --restore|-restore|restore|-r)
bt_start
  ;;

  --help|-help|help|-h)
echo "[Qt]SixA Daemon"
$0
  ;;

  --version|-version|version|-v)
echo "[Qt]SixA Daemon - version 1.5.1"
  ;;

  *)
echo "usage: $0 <command>

command can be:
    -h, --help          Show help (this message)
    -v, --version       Show sixad version

    -s, --start         Start sixad
        --stop          Stop sixad
        --remote        BD Remote mode

    -r, --restore       Restore regular bluetooth

You can also check: sixad-raw, sixad-notify"
  ;;

esac
