#!/bin/bash

# You need to configure these variables for this script to work.
DBUSER=name@domain.de
DBPASS="password"
DBROOT=/home/$USER/Dropbox

# get cookie
COOKIE=~/.curl_dropbox_cookies.txt
if [ ! -f "$COOKIE" ]
then
    echo "Getting cookies for the $DBUSER Dropbox account..."
    curl --cookie-jar "$COOKIE" \
        --data-urlencode "login_email=$DBUSER" \
        --data-urlencode "login_password=$DBPASS" \
        "https://www.dropbox.com/login" -o /dev/null -s
fi

# prepare temporary directory
argTime=`date -d "$1" +%Y%m%d-%H%M%S`
shift
tmpOld=/tmp/Dropbox_$argTime
tmpNew=/tmp/Dropbox
rm -rf $tmpOld
rm -rf $tmpNew

# search each file
for file in `find $@ -type f`
do
    relFile=$(echo ${file: -$((${#file} - ${#DBROOT} - 1))} | sed s,\ ,%20,g)
    echo Searching version $argTime of $relFile...
    s=1
    unset finished url
    while [ ! $finished ]
    do
        list=`curl -s -L --cookie "$COOKIE" \
            "https://www.dropbox.com/revisions/$relFile?s=$s" | \
            awk '
                /180px/ {
                    getline
                    gsub(/^[ \t]+|[ \t]+$/,"")
                    gsub(/\ /, "_")
                    gsub(/_hr/, "_hour")
                    printf "%s;",$0
                }
                /s_magnifier/ {
                    gsub(/\"/, " ")
                    print $3
                }
            '`
        finished=0
        unset urlTime
        for line in $list
        do
            humanTime=`echo $line | cut -d';' -f1 | sed -e 's/_/ /g'`
            urlTime=`date -d "$humanTime" +%Y%m%d-%H%M%S`
            if [[ "$urlTime" < "$argTime" ]]
            then
                url=`echo $line | cut -d';' -f2`
                finished=1
                break
            else
                unset finished url
            fi
        done
        let s=s+1
    done
    if [ $url ]
    then
        echo Downloading version $urlTime of $relFile...
        mkdir -p $tmpOld/`dirname $relFile` 
        curl --cookie "$COOKIE" "$url" -o "$tmpOld/$relFile" -s
    else
        echo File was not existing at $argTime...
    fi
    mkdir -p $tmpNew/`dirname $relFile` 
    ln -s $DBROOT/$relFile $tmpNew/$relFile
done

#compare revisions
meld $tmpNew $tmpOld

