#!/bin/sh
# Wrap "dbxcli get" command to download files from a dropbox dir
# Solves https://github.com/dropbox/dbxcli/issues/60
#
# Published at https://gist.github.com/shadiakiki1986/c22fa50523dc7f80ceda6b940358eedf
#
# Tested on
#   dbxcli version: v2.1.1
#   SDK version: 4.5.0
#   Spec version: a1d5111

set -e # abort script on error in dbxcli ls call

if [ -z "$1" ] | [ -z "$2" ]; then
  echo "Missing arguments"
  echo "Usage dbxcli-getdir path/to/source/on/dropbox path/to/target/on/local"
  exit 1
fi

if [ ! -d "$2" ]; then
  echo "Target directory $2 does not exist. Aborting"
  exit 2
fi

SOURCE=$1
TARGET=$2
echo "Downloading files from '$SOURCE' to '$TARGET'"

# test ls to abort if inexistant folder
dbxcli ls -l "$SOURCE"

# execute
dbxcli ls -l "$SOURCE"|grep ago|awk -F"ago" "{print \$2}"|sed -e "s/^[[:space:]]*//" -e "s/[[:space:]]*$//"|xargs -I{} dbxcli get {} $TARGET
echo "Download complete"