#!/bin/bash

echo "`basename $0` (c)2006-2012 PaulTT"

if [ $# -lt 2 ]; then
	set ""
fi

case $1 in
	-l|ls|list|-g|get|-p|put|-d|-k|del);;
	*)
		echo "Usage: "
		echo "  `basename $0` <ls|get|put|del> <remote folder> [files]"
	        echo "  . when <files> is '-a' or blank will act on all files in <remote folder>"
		echo ""
		exit 1
	;;
esac

PTT_LSFILE=/tmp/_PTT_TEMP_BLUE1_$$

# init device variables
PTT_BLUEDEV=""
PTT_BLUECHAN=""
if [ -f ~/.config/ptt.d/pttbluetool.conf ]; then
	. ~/.config/ptt.d/pttbluetool.conf
elif [ -f /etc/ptt.d/pttbluetool.conf ]; then
	. /etc/ptt.d/pttbluetool.conf
else
	echo -n "Config file not found, please tell me bt device mac address: "
	read PTT_BLUEDEV
	echo -n "and communication channel: "
	read PTT_BLUECHAN
fi

case $1 in
	-l|ls|list)
		PTT_ACTION="-l"
	;;
	-g|get)
		PTT_ACTION="-g"
	;;
	-p|put)
		PTT_ACTION="-p"
	;;
	-d|-k|del)
		PTT_ACTION="-k"
	;;
esac
shift

PTT_FOLDER=$1
shift

if [ "x$1" = "x" -a "$PTT_ACTION" != "-l" ]; then
	echo "Please specify a file to act on or '-a' which means all!"
	echo ""
	exit 1
fi

if [ "$1" = "-a" ]; then
	echo "Getting file list..."
	obexftp -b $PTT_BLUEDEV -B $PTT_BLUECHAN -c $PTT_FOLDER -l > $PTT_LSFILE;
	PTT_IFS=$IFS
	IFS=$'\n'
	for i in `grep "file name=" $PTT_LSFILE`; do
	# TODO add to parm list the files
		#PTT_FILE=`echo `echo $i | cut -d"\"" -f2`;
		echo `echo $i | cut -d"\"" -f2`
	###	obexftp -b $PTT_BLUEDEV -c $PTT_FOLDER $PTT_ACTION `echo $i | cut -d"\"" -f2`
	done
	IFS=$PTT_IFS
	echo $@
	echo "suka again"
	rm -f $PTT_LSFILE;
	exit
fi

if [ "$PTT_ACTION" = "-l" ]; then
	obexftp -b $PTT_BLUEDEV -B $PTT_BLUECHAN -c $PTT_FOLDER $PTT_ACTION;
	exit
fi

for i in $@ ; do
	obexftp -b $PTT_BLUEDEV -B $PTT_BLUECHAN -c $PTT_FOLDER $PTT_ACTION $i;
done

