#!/usr/bin/env python3

import sys
import argparse
import subprocess
import os
import os.path as path

def isset(argv, key):
    value = argv[key]
    return (value is not None) and (value is not False)

def print_help():
    """USAGE

    xscp [options] <source> <target>

OPTIONS

    -e, --exclude <files>
        Exclude files from search. File paths must be specified relative to the
        source directory. Multiple files are separated by "," with no space in
        between.

    source
        Source directory.

    target
        Target directory.

EXAMPLE: Exclude files from search

    xscp -e foo,bar ../source target
    """
    print(print_help.__doc__)

def init_argparse():
    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument(
        "-e",
        "--exclude",
        type=str,
        required=False
    )

    parser.add_argument(
        "-h",
        "--help",
        action="store_true",
        required=False
    )

    parser.add_argument(
        "targets",
        nargs="*"
    )

    stderr = sys.stderr;
    stdout = sys.stdout;

    devnull = open(os.devnull, "w")
    sys.stderr = devnull;
    sys.stdout = devnull;

    argv, error = None, False
    try:
        argv = vars(parser.parse_args())
    except:
        error = True

    sys.stderr = stderr;
    sys.stdout = stdout;

    if error:
        print("[ERROR] Invalid argument. See 'xscp -h' for usage.")
        quit(1)

    return argv

separator = path.sep

if __name__ == "__main__":
    argv = init_argparse()

    if isset(argv, "help"):
        print_help()
        quit(0)

    targets = argv.get("targets")
    num_targets = len(targets)

    if num_targets != 2:
        print("[ERROR] Expected 2 arguments, got {}".format(num_targets))
        quit(1)

    source, target = targets

    source = source.rstrip(separator)

    if not path.exists(source):
        print("[ERROR] Invalid source path")
        quit(1)

    if not path.isdir(source):
        print("[ERROR] Source path is not a directory")
        quit(1)

    rootname = path.basename(source)

    excluded = []
    if isset(argv, "exclude"):
        paths = [ x.lstrip(separator) for x in argv.get("exclude").split(",") ]
        for filename in paths:
            excluded.append(separator + rootname + separator + filename)

    command = "rsync -av "

    for item in excluded:
        command += "--exclude={} ".format(item)

    command += "{} {}".format(source, target)

    print(command)

    command = command.split(" ")

    subprocess.call(command)
