#! /bin/bash
readonly ClientID=a121b240
readonly ClientSecret=167a85400632f68f1558468521779c91
readonly API=https://developer.api.bitcasa.com/v1

localpath="$1"
filelist="$2"
tokenfile="accesstoken.txt"

access_token=$(< $tokenfile)
while true 
do
#lock
	while ! ln $filelist ${filelist}.lock 
	do
		sleep 10
	done
	LINE=$(head -n 1 $filelist)
 	echo "$(tail -n +2 $filelist)" >$filelist
	rm -f ${filelist}.lock
	
	if [ -z "$LINE" ]; then
		break
	fi

	if [[ "$LINE" =~ \t ]]; then
		remotetarget=$(cut -f1 <<<"$LINE")
		localtarget=$(cut -f2 <<<"$LINE")
		echo download $localtarget
		if [[ "$localtarget" =~ / ]]; then
			[ -d "$localpath/${localtarget%/*}" ] || mkdir -p "$localpath/${localtarget%/*}"
		fi
		while true
		do
			curl -f -G "${API}/files/test?access_token=$access_token" --data-urlencode "path=$remotetarget" -o "$localpath/$localtarget"
			case $? in
				0 ) break ;;
			esac	
		done
	fi
done
