#!bin/python

# dirsync <fromdir> <todir>

# rsyncs the files (no delete) and then pings photo site on all the
# modified ones

import sys, subprocess, os, restkit, logging, urllib
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
fromDir, toDir = sys.argv[1:3]
assert fromDir.endswith('/')
assert toDir.endswith('/')

sync = restkit.Resource("http://bang:9042/")

out = subprocess.check_output(['/usr/bin/rsync',
                               '-v',
                               '--recursive',
                               '--links',
                               '--times',
                               fromDir, toDir])
errored = []
for line in out.splitlines():
    target = os.path.join(toDir, line.strip())
    if os.path.isfile(target):
        try:
            sync.post(payload=urllib.urlencode([('file', target)]),
                      headers={'Content-Type': 'application/x-www-form-urlencoded'},
            )
        except restkit.errors.RequestFailed:
            errored.append(target)
if errored:
    log.error("These files failed to post to photo site:")
    for f in errored:
        log.error(f)

