#!/bin/bash

MODE=BL_MAN
FILE=/etc/lcriqbl.conf
FILELCRIQNAME=/etc/lcriqname

if test -f "$FILE"; then
    MODE=`cat $FILE`
fi

if test -f "$FILELCRIQNAME"; then
    LCRIQNAME=`cat $FILELCRIQNAME`
else
    LCRIQNAME=""
fi

if [ "$LCRIQNAME" == "" ]; then
    macw=$(cat /sys/class/net/eth0/address)
    macw=${macw//:/-}
    LCRIQNAME="LCRIQ-$macw"
fi

case $MODE in
  BL_MAN)
    echo "Bluetooth mode Manual"
    ;;
  BL_ACN)
    echo "Bluetooth mode Auto-Connect"
    ;;
  *)
    MODE=BL_MAN
    echo "Invalid Bluetooth mode switching to default"
    ;;
esac

###echo "set name to $LCRIQNAME"
###hciconfig hci0 name $LCRIQNAME

echo "mode $MODE settings"
if [ "$MODE" == "BL_ACN" ]; then
    hciconfig hci0 piscan
#    hciconfig hci0 noauth
else
    hciconfig hci0 noscan
fi

#if /bin/mknod -m 666 /dev/rfcomm1 c 216 1 ; then
#    echo "/dev/rfcomm1 created!"
#else
#    echo "/dev/rfcomm1 already exist!"
#fi

echo "SPP settings"
rm -fr /dev/rfcomm1
# register SerialPort Profile
/usr/bin/sdptool add --channel=3 SP

echo "rfcomm bind /etc/bluetooth/rfcomm.conf"
if [ -f /etc/bluetooth/rfcomm.conf ]; then
    device=`grep device /etc/bluetooth/rfcomm.conf | awk '{print $2;}' | tr -d \;`
    channel=`grep channel /etc/bluetooth/rfcomm.conf | awk '{print $2;}' | tr -d \;`
    echo "rfcomm bind 0 $device $channel"
    rfcomm bind 0 $device $channel
else
    echo "file /etc/bluetooth/rfcomm.conf does not exist."
fi

echo "socat ptys"
socat -d -d PTY,link=/dev/ttyRFCOMM1,raw,echo=0 PTY,link=/dev/vrfcomm1,raw,echo=0 &

echo "rfcomm watch"
/usr/bin/rfcomm watch rfcomm1 3 socat /dev/ttyRFCOMM1,raw,echo=0 /dev/rfcomm1,raw,echo=0
