#!/usr/bin/python

import os, argparse, shutil

parser = argparse.ArgumentParser(description='Transfer RRD files between hosts with different architectures. This script transfers all RRDs in the given directory in LOCALHOST to the specified directory on specified host. The structure of local directory is transferred as well. Internally, it uses SSH to transfer the data. For convenience, insure that you could login into the specified host using SSH keys. The remote and local hosts have to have RRDTOOL installed.')

parser.add_argument('directory', help='directory on localhost containing RRDs')
parser.add_argument('remote_host', help='remote host')
parser.add_argument('remote_dir', help='directory on remote host to which RRDs are transferred')

args = parser.parse_args()

srcdir = args.directory
tgthost = args.remote_host
tgtdir = args.remote_dir
tmpdir = srcdir + "-rrd-sync-tmp"
helper_script = "rrd-sync-run.sh"

print "Copy from", srcdir, " to %s:%s" % (tgthost,tgtdir)

def cmd(c):
    print "Execute:", c
    os.system(c)

# phase 1: prep tmp dir
shutil.rmtree( tmpdir, ignore_errors = True )
os.mkdir( tmpdir )
fscript = open( os.path.join( tmpdir, helper_script ), "w" )
fscript.write("#!/bin/bash\n#\n# This is auto-generated by rrd-sync\nset -e\n")

for root, dirs, files in os.walk(srcdir):
    rr = os.path.relpath(root, srcdir)
    print rr, root, srcdir
    for di in dirs:
        d = os.path.join(tmpdir, rr, di)
        print "Creating dir:", d
        os.mkdir(d)
    print

    for fi in files:
        ftgt = os.path.join(tgtdir, rr, fi)
        ftmp = os.path.join(tmpdir, rr, fi + ".xml.gz")
        fsrc = os.path.join(root, fi)
        if os.path.splitext(fi)[1] == ".rrd":
            print fsrc, "-->", ftgt
            cmd( "rrdtool dump '" + fsrc + "' | gzip > '" + ftmp + "'" )
            fscript.write("echo " + ftgt + "\n")
            fscript.write( "zcat '" + ftgt + ".xml.gz' |  rrdtool restore -f - '" + ftgt + "'\n" )

fscript.close()

# phase 2: rsync
cmd( "scp -r '" + tmpdir + "/'* " + tgthost + ":" + tgtdir + "/" )

# phase 3: run extractor on host
cmd( "ssh " + tgthost + " bash '" + os.path.join( tgtdir, helper_script ) + "'" )

# cleanup
shutil.rmtree( tmpdir, ignore_errors = True )

