gps_id='00:0D:B5:33:A2:29'
device='rfcomm0'

trap 'sudo killall gpsd;sudo rfcomm release $gps_id;sudo hcitool dc $gps_id; exit 1' 2

while [ 1 ]
do

  echo "killing gpsd"
  sudo killall gpsd
  echo "searching gps mouse"
  found=0
  while [ $found -le 0 ]
  do
    s=`sudo hcitool scan`
    echo $s
    if [[ $s = *$gps_id* ]]
    then
      echo "---found---"
      found=1
    fi
  done

  echo "-> pairing..."
  sudo hcitool cc $gps_id
  sudo hcitool info $gps_id
  sudo hcitool con
  sudo l2ping $gps_id -c 3
  echo "-> paired"

  sudo rfcomm bind /dev/$device $gps_id
  echo "connection established"


  #sudo rfcomm
  #sudo ln -s /dev/device ~/.wine/dosdevices/com1
  sudo gpsd -b /dev/rfcomm0 # -D 1 -N

  loop=1
  status=''
  while [ $loop -ge 1 ]
  do
    sleep 1
    prestatus=$status
    status=`sudo rfcomm`
    if [[ "$status" != "$prestatus" ]]
      then
        echo "$status"
    fi
    loss="$(sudo l2ping $gps_id -c 1 -t 1 2>&1)"
    if [[ $loss = *'Host is down'* ]]
      then
        echo "D O W N"
        sudo rfcomm release $gps_id;sudo hcitool dc $gps_id
        loop=0
      
      fi

  done
done