#!/usr/bin/awk -f
# usage: sdptool search DUN | bt-find-dun.awk >> /etc/bluetooth/rfcomm.conf
#
# Copyright (C) James Budiono 2013
# License: GPL Version 3 or later.
#

BEGIN { 
	# configuration
	RFCOMM_CONF="/etc/bluetooth/rfcomm.conf"
	DEVICE_NAMES="/var/lib/bluetooth/*/names"
	
	# get all known device names
	while ("cat " DEVICE_NAMES | getline) {
		addr=$1
		sub(/^[^ ]* /,"",$0)
		devices[addr]=$0
	}
	
	# get all existing rfcomms
	while ("cat " RFCOMM_CONF | getline) {
		if (match($0,"^[ \t]*#[ \t]*")) continue		# ignore comment
		if (match($1,"rfcomm[0-9]")) rfcomm=$1
		if (match($1,"device")) {
			existing[rfcomm]=$2
			existing2[$2]=rfcomm
		}
	}
	
	# init rfcomm_id
	rfcomm_id=0
}

# get device name, if any
function get_name(addr) {
	if ( devices[addr] == "" ) return addr
	else return devices[addr]
}

# get the next available rfcomm id
function get_next_rfcomm_id() {
	while ( existing["rfcomm" rfcomm_id] != "" ) rfcomm_id++
	return rfcomm_id
}

/Searching for DUN on/ { bt_address=$5 }
/Channel/ {
	# Got one
	if ( existing2 [ bt_address ";" ] == "" ) {
		print "Found DUN on " bt_address " (" get_name( bt_address ) ") channel " $2 > "/dev/stderr"
		print "rfcomm" get_next_rfcomm_id() " {"
		print "    bind yes;"
		print "    device " bt_address ";"
		print "    channel " $2 ";"
		print "    comment \"rfcomm from " get_name( bt_address ) "\";"
		print "}"
	} else {
		print "Ignoring " bt_address " (" get_name( bt_address ) ") - already recorded as " existing2 [ bt_address ";" ] "." > "/dev/stderr"
	}		
}
