#!/bin/sh

MODULE_NAME=bluetooth

PATH_USR_BIN=/usr/bin
PATH_MOD_BIN=/opt/$MODULE_NAME/bin
PATH_MOD_ETC=/opt/$MODULE_NAME/etc
PATH_BLUETOOTH_ITF=/sys/class/bluetooth/hci*
MODULE_CFG=$PATH_MOD_ETC/settings
BLUETOOTH_CFG=$PATH_MOD_ETC/bluetooth.conf

DBUS_DAEMON=dbus-daemon
BLUETOOTH_DAEMON=bluetoothd
BLUETOOTH_SPRITE=btsprite

case "$1" in

  start)
    echo -n "Starting Bluetooth support... "
    . $MODULE_CFG
    if [ "$MOD_BLUETOOTH_ENABLED" != "1" ]; then
      echo "skipped"
      exit 0
    fi
    insmod /lib/modules/*/kernel/drivers/bluetooth/btintel.ko
    insmod /lib/modules/*/kernel/drivers/bluetooth/btusb.ko
    mkdir -p /var/run/dbus
    killall -q -0 $DBUS_DAEMON || $PATH_USR_BIN/$DBUS_DAEMON --nopidfile --fork --syslog-only --config-file=/usr/share/dbus-1/system.conf
    i=0
    while ! ls $PATH_BLUETOOTH_ITF &>/dev/null; do
        i=$(( i + 1 ))
        if [ $i -eq 10 ]; then
          echo "error"
          exit 1
        fi
        sleep 1
    done
    $PATH_MOD_BIN/$BLUETOOTH_DAEMON -f $BLUETOOTH_CFG -P a2dp,avrcp,wiimote,hostname,mcp,vcp,micp,bass,bap,csip &
    sleep 1
    if [ "$MOD_BLUETOOTH_DISCOVERABLE" = "1" ]; then
      $PATH_USR_BIN/bluetoothctl discoverable on >/dev/null
    else
      $PATH_USR_BIN/bluetoothctl discoverable off >/dev/null
    fi
    $PATH_USR_BIN/bluetoothctl pairable off >/dev/null
    $PATH_USR_BIN/bluetoothctl agent off >/dev/null
    if [ ! -z "$MOD_BLUETOOTH_ALIAS" ]; then
      $PATH_USR_BIN/bluetoothctl system-alias "$MOD_BLUETOOTH_ALIAS" >/dev/null
    else
      $PATH_USR_BIN/bluetoothctl reset-alias >/dev/null
    fi
    [ "$MOD_BLUETOOTH_PAN_ENABLED" != "1" ] || $PATH_MOD_ETC/pan start
    $PATH_MOD_BIN/$BLUETOOTH_SPRITE &
    echo "done"
    exit 0;
  ;;

  stop)
    echo -n "Stopping Bluetooth support... "
    killall -q -SIGTERM $BLUETOOTH_SPRITE
    i=0
    while killall -q -0 $BLUETOOTH_SPRITE 2>/dev/null && [ $i -lt 5 ]; do
      i=$(( i + 1 ))
      sleep 1
    done
    $PATH_MOD_ETC/pan stop
    killall -q -SIGTERM $BLUETOOTH_DAEMON
    killall -q -SIGTERM $DBUS_DAEMON
    rmmod btusb.ko
    rmmod btintel.ko
    echo "done"
    exit 0;
  ;;

  restart)
    $0 stop
    sleep 2
    $0 start
  ;;

  status)
    if ! killall -q -0 $DBUS_DAEMON; then
      echo "D-Bus daemon not running"
      exit 1;
    fi
    if ! killall -q -0 $BLUETOOTH_DAEMON; then
      echo "Bluetooth daemon not running"
      exit 1;
    fi
    if ! killall -q -0 $BLUETOOTH_SPRITE; then
      echo "Bluetooth helper daemon not running"
      exit 1;
    fi
    if bluetoothctl show | grep -q "Powered: no"; then
      echo "Bluetooth adapter is off"
      exit 1;
    fi
    echo "Bluetooth support fully running"
    exit 0;
  ;;

  defaults)
    cp /opt/$MODULE_NAME/etc/defaults $MODULE_CFG 2>/dev/null
    exit 0
  ;;

  *)
    echo "Usage: $0 {start|stop|restart|status|defaults}"
    exit 1
  ;;

esac
