#! /bin/bash

readonly ClientID=a121b240
readonly ClientSecret=167a85400632f68f1558468521779c91
readonly API=https://developer.api.bitcasa.com/v1
tokenfile="accesstoken.txt"
access_token=$(< $tokenfile)

remotepath="/Bitcasa Infinite Drive/$1"
listfile="$2"
prefix="$3"

declare -A list_name
declare -A list_category
declare -A list_folder
jsondata=''

function finddirname(){
	local target=$1
	local parent=${target%/*}
	local targetname=${target##*/}
	
	local parentpath='/'
	if [ -z "$parent" ]; then
		parent='/'
	else
		parentpath=$(finddirname "$parent")
	fi
	local ret=$(curl -s ${API}/folders${parentpath} -G -d access_token=$access_token)
        if [[ $ret =~ \"error\"\ *:\ *null ]]; then
		jsondata="$ret"
		parsefolderlist "$parentpath"
		local item_enc=(${list_folder["$parentpath"]})
		local enc_path=''
		for item in "${item_enc[@]}"
		do
			if [[ "${list_name[$item]}" = $targetname ]]; then
				enc_path="$item"
				break
			fi
		done
		if [ -n "$enc_path" ]; then
			echo "$enc_path"
			return 0
		fi
        fi
	echo $ret >&2
}

function parsefolderlist(){
	local path=''
	local name=''
	local category=''

	local LINE=''
	local folderitem=()
	while read LINE
	do
		LINE=$(sed -e 's/"\?, "/\n/g' <<<"$LINE")
		path=$(sed -n -e 's/^path": "\(.*\)/\1/p' <<<"$LINE")
                name=$(sed -n -e 's/^name": "\(.*\)/\1/p' <<<"$LINE")
                category=$(sed -n -e 's/.*category": "\(.*\)/\1/p' <<<"$LINE")

		if [ -z "$path" ]; then
			echo "$LINE" >&2
			break
		fi

		name="$(sed 's/\xd7/×/g' <<<"$name")"

                folderitem=("${folderitem[@]}" "${path}")
                list_name[${path}]="$name"
                list_category[${path}]=$category
	done < <(echo -e "$jsondata" | sed -e 's/}, {/\n/g' | sed -e 's/.*\[{//' )
	list_folder["$1"]="${folderitem[@]}"
}

encpath=$(finddirname "$remotepath")


function finddirname(){
	local target=$1
	local parent=${target%/*}
	if [[ $target = $encpath ]]; then
		return 0
	fi
	if [ -z "$parent" ]; then
		return 0
	fi
	echo $(finddirname $parent)${list_name[$target]}'/'
}

ret=$(curl -s ${API}/folders${encpath} -G -d access_token=$access_token -d depth=0)
if [[ $ret =~ \"error\"\ *:\ *null ]]; then
	jsondata="$ret"
	parsefolderlist "$encpath"
	item_enc=(${list_folder["$encpath"]})
	for item in "${item_enc[@]}"
	do
		case ${list_category[$item]} in
			folders )
				continue
			;;
		esac
		echo -e "$item\t""$prefix$(finddirname ${item%/*})${list_name[$item]}" >>$listfile
	done
fi
