 mime = require 'mime'
 process = require 'process'
 uuid = require 'node-uuid'
+async = require 'async'
 log = require('printit')
     prefix: 'Data Proxy'
 

    buildFsTree devicename, { filePath: filePath }, (err, res) ->

        # Fetch only files
        db.db.query { map: (doc) ->

            if doc.docType is 'File'
                emit doc._id, doc

        }, (err, res) ->
            for doc in res.rows
                doc = doc.value
                if not filePath? or filePath is path.join doc.path, doc.name
                    filePath = path.join remoteConfig.path, doc.path, doc.name
                    if doc.binary?
                        binaryUri = "cozy/#{doc.binary.file.id}/file"
                        # Fetch binary via CouchDB API
                        client.saveFile binaryUri, filePath, (err, res, body) ->
                            if err
                                console.log err

                            # Rebuild FS Tree to correct utime
                            buildFsTree devicename, { filePath: path.join doc.path, doc.name }, callback


putDirectory = (devicename, directoryPath, recursive, callback) ->

    dirLastModification = stats.mtime

    # Lookup for existing directory
    db.db.query { map: (doc) -> emit doc._id, doc if doc.docType is 'Folder' }, (err, res) ->
        for doc in res.rows
            doc = doc.value
            if doc.path is dirPath and doc.name is dirName
