#!/usr/bin/env python
# Plan
# Dictionary of src item consisting of target_name + list of sources (in rsync format)
# e.g. { "ahab" : ["/home/tz/backup/daily"], "svn_rp" : ["root@codeabode.net:/home/codeabode/backup/svn"]}

import os.path
import sys
import os
import shutil

VERBOSE = True

def get_current_date(seperator = ""):
    """Get current date in format yyyy-mm-dd with '-' replaced by separator
    parameter"""
    import time
    now = time.localtime(time.time())
    today = time.strftime("%Y" + seperator + "%m" + seperator + "%d", now)
    return today

def run(cmd):
    if os.system(cmd):
        print 'Error on command: %s' % cmd

def _print(s, force=False):
    if VERBOSE or force:
        print(s)

def mirror(src, dest):
    '''Mirror src to dest using rsync.

    @param src: rsync src string. Should have a trailing slash on path as o/w
    src will be put inside dest)
    '''
    # --delete: delete files not at destination
    # -e ssh: login using ssh and private key if necessary
    # -u: update only
    # -z: use compression
    # note that /* is very different from / for rsync deletion purposes
    sync = "rsync -uz -e ssh --recursive --delete %s %s" % (src, dest)
    run(sync)

def collect_backups(sourceList, dest_base_path):
    '''rsync a whole collection of backups specified by sourceList.

    TODO? remove destination directories for which there is no source (i.e.
    from previous occasions) need to think about this as it assume all files
    have come via this system (and e.g. for laptop use a bit of shell script to
    pick up the files ...)
    '''
    if not(os.path.exists(dest_base_path)):
        os.makedirs(dest_base_path)
    for key in sourceList.keys():
        for source in sourceList[key]:
            _print("Source file is: " + source)
            dest = os.path.join(dest_base_path, key)
            mirror(source, dest) 

import unittest
import tempfile
class TestArchiveCollector(unittest.TestCase):

    def setUp(self):
        self.destBasePath = tempfile.mkdtemp()
        self.destPath = os.path.join(self.destBasePath, 'out')
        inPath = os.path.join(self.destBasePath, 'in')
        os.makedirs(inPath)
        self.sourceList = { 'instuff' : [inPath + '/'] }

    def tearDown(self):
        shutil.rmtree(self.destBasePath)
    
    def test_collect_backups(self):
        collect_backups(self.sourceList, self.destPath)
        assert os.path.exists(self.destPath)
        outpath = os.path.join(self.destPath, 'instuff')
        assert os.path.exists(outpath)


