from os import environ
from subprocess import Popen
from shlex import split as shplit

# Remote syncing, when needed

def sync():
    """ Remote syncing """
    DEST = environ.get('DEST')
    REMOTE_HOST = environ.get('REMOTE_HOST', False)
    if REMOTE_HOST:
        REMOTE_USER = environ.get('REMOTE_USER')
        REMOTE_PASS = environ.get('REMOTE_PASS')
        print('Remote host %s configured : will sync with it' % REMOTE_HOST)
        paths = [DEST]
        SYNC_EXTRA_PATHES = environ.get('SYNC_EXTRA_PATHES', False)
        if SYNC_EXTRA_PATHES:
            paths +=  SYNC_EXTRA_PATHES.split(',')
        def run(path):
            print('Syncing %s...' % path)
            _paths = path.split(':')
            lpath = _paths[0]
            rpath = _paths[1] if len(_paths) > 1 else 'backups'
            command = ('sshpass -p %s rsync -av --delete -e '
                       '"ssh -p 23 -o StrictHostKeyChecking=no" '
                       '%s %s@%s:./%s') % (REMOTE_PASS, lpath, REMOTE_USER, REMOTE_HOST, rpath)
            p = Popen(shplit(command))
            p.communicate()
        map(run, paths)
