#!/bin/bash

SYS_CONF="/etc/bluetooth.conf"
BOOT_CONF="/boot/bluetooth.conf"
CONF="/data/etc/bluetooth.conf"
RUN_CONF="/var/lib/bluetooth.conf"

ADAPTER="hci0"
PROG="/usr/libexec/bluetooth/bluetoothd"
PROG_HC="/usr/bin/hciconfig"
DATA_DIR="/var/lib/bluetooth"
RUN_DATA_DIR="/data/bluetooth"
NO_ON_BOARD_BT="/tmp/.no_on_board_bt"  # used by RPi to explicitly indicate that no on-board BT was detected


test -x ${PROG} || exit 0

test -n "${OS_VERSION}" || source /etc/init.d/base

prepare_conf ${CONF} ${SYS_CONF} ${BOOT_CONF}
test -s ${CONF} || exit 0


configure() {
    mkdir -p ${RUN_DATA_DIR}
    ln -sf ${RUN_DATA_DIR} ${DATA_DIR}
    cp ${CONF} ${RUN_CONF}

    # if no specific name configured, use hostname
    if ! grep -E 'Name\s*=' ${RUN_CONF} &>/dev/null; then   
        sed -ri "s/(\[General\])/\1\nName = $(hostname)/" ${RUN_CONF}
    fi
    
    # bring adapter up
    ${PROG_HC} ${ADAPTER} up
}

start() {
    msg_begin "Configuring bluetooth"

    # wait up to 10 seconds for device
    count=0
    while ! ${PROG_HC} ${ADAPTER} &>/dev/null; do
        # on RPi boards, the absence of an on-board BT can be detected earlier, preventing 10s timeout
        
        count=$((count + 1))
        if [[ ${count} -ge 10 ]] || [[ -f "${NO_ON_BOARD_BT}" ]]; then
            msg_fail "no device"
            logger -t bluetooth "bluetooth device not available"
            return 0
        fi

        sleep 1
    done
    
    if configure; then
        msg_done
    else
        msg_fail
        return 1
    fi

    msg_begin "Starting bluetoothd"
    ${PROG} &>/dev/null &
    msg_done

    # if DiscoverableTimeout is set to 0, make adapter discoverable from boot time
    if grep -E '^DiscoverableTimeout\s*=\s*0$' ${RUN_CONF} &>/dev/null; then
        sleep 1
        ${PROG_HC} ${ADAPTER} piscan
    fi
}

stop() {
    msg_begin "Stopping bluetoothd"
    killall -q $(basename ${PROG})
    test $? == 0 && msg_done || msg_fail
}

case "$1" in
    start)
        start
        ;;
        
    stop)
        stop
        ;;
        
    restart)
        stop
        start
        ;;
    
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

