#!/bin/sh
# export LD_LIBRARY_PATH=/mnt/usbfs/affix-release/lib $*
# export PATH=$PATH:/mnt/usbfs/affix-release/bin $*

xx=0
day_cycle=0
avoid_dup=0
while xx=0
number_of_bt_addr=0
number_of_new_bt_addr=0  
do
	cd /tmp
#	let "day_cycle = day_cycle + 1"

#	if [ $day_cycle = 1440 ]
#	then 
#		rm addr_cum.bt
#	fi
	day_cycle=`date -I +1%H%M%S`
	if [ $day_cycle -lt 1000200 ]
	then
		if [ $avoid_dup -eq 0 ]
		then
			rm addr_cum.bt
		fi
		avoid_dup=1
	else
		avoid_dup=0
	fi
	

	echo $day_cycle: Discovering Bluetooth Addresses
	btctl discovery 8 >disc.txt
	echo '#!/bin/sh' > send_wc.sh
	chmod 777 send_wc.sh
	cat addr_cum.bt > addr_temp.bt
	sed -n 's/^.*\(..:..:..:..:..:..\).*$/\1/p' disc.txt > addr_temp2.bt
	number_of_bt_addr=`grep -c "" addr_temp2.bt`
	cat addr_temp2.bt >> addr_temp.bt
        cat  addr_temp.bt | sort | uniq > addr_cum.bt
	cat  addr_temp.bt | sort | uniq -d > addr_dup.bt
	cat  addr_dup.bt >> addr_temp2.bt 
	cat addr_temp2.bt | sort | uniq -u > addr.bt
	number_of_new_bt_addr=`grep -c "" addr.bt`
	echo Found $number_of_bt_addr Bluetooth Addresses, $number_of_new_bt_addr are new
	
	sed -e 's:.*:btctl push & /mnt/usbfs/incoming/welcome.vcf:' addr.bt >> send_wc.sh
	./send_wc.sh
# echo Going to Sleep .....
# sleep 60
done
