#!/usr/bin/env python
"""
Inject file into account without possessing the original data.
"""
# Copyright (C) 2011 by Wladimir van der Laan
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import logging
import json

from dropbox.exceptions import *
from dropbox.metadataclient import MetadataClient

if __name__ == '__main__':
    from config import host_id,root_ns
    import sys
    from sys import stderr as err, stdout as out
    
    logging.basicConfig(level=logging.INFO, # Change to DEBUG to show details
        datefmt='%a, %d %b %Y %H:%M:%S',
        format='%(asctime)s %(levelname)-8s %(name)-8s %(message)s',
        stream=sys.stdout)
    
    server = "client-lb.dropbox.com"
    try:
        infile = sys.argv[1]
    except IndexError:
        err.write('Usage: %s <infile.json> [<path>]\n' %
            sys.argv[0])
        exit(1)

    if len(sys.argv)>2:
        path = sys.argv[2]
    else:
        path = None        
    
    if infile == '-':
        f = sys.stdin
    else:
        f = open(infile, 'r')
    try:
        indata = json.load(f)
    except ValueError,e:
        err.write('Error parsing input file: %s\n' % e)
        exit(1)
    f.close()

    if path is None:
        path = indata['name']
    if not path.startswith('/'):
        path = '/' + path

    s = MetadataClient(server, host_id, root_ns)
    try:
        s.inject_file(path, indata['blocks'], indata['size'], 
            indata.get('mtime', None))
    except (APIError,UnknownBlocksError),e:
        err.write('%s\n' % e)
        exit(1)

    out.write("File %s dropshipped succesfully.\n" % path)
    