#!/bin/bash

set -e

if test "$1" != start -a "$1" != stop; then
    die "Usage: $(basename $0) [start|stop]"
fi

if test "$1" = start -o "$1" = on; then
    load-wireless-driver bluetooth enable
    hciconfig -a
    hciconfig hci0 up

    touch /data/do-bt-scan
    while test -e /data/do-bt-scan; do
	hcitool scan
    done >/dev/null 2>&1 &
else
    set +e
    rm /data/do-bt-scan || true
    
    ret=1
    for x in $(seq 1 10); do
	if test $x != 1; then
	    echo try $x
	fi
	hciconfig hci0 down || true
	if rmmod bt8xxx; then
	    ret=0
	    break;
	fi
	sleep 1;
	killall hcitool || true;
    done
    load-wireless-driver bluetooth disable
    test $ret = 0
    true
fi
