#!/usr/bin/python

import sys
import os
import re
import uuid
import subprocess

try:
    __import__("argparse")
except ImportError:
    print "Argparse module is not installed please install it via 'sudo pip \
install argparse'"

    sys.exit()

import argparse

reg = re.compile("^export ([^=]+)='(.+)'$")
fenv = open(os.path.expanduser("~") + "/.overcast-env")
env = {}
args = None
for varline in fenv:
    m = reg.match(varline)
    if m is None:
        continue
    env[m.group(1)] = m.group(2)

def cpFile(source, pod, target, kill, v):
    # remove trailing slash from source(if exists)
    if source.endswith('/'):
        source = source[:-1]
    source_dir = os.path.dirname(source)
    if source_dir == "":
        source_dir = os.getcwd()
    source = os.path.basename(source)
    if os.path.isdir(source):
        target += "/"
    tmp_tgz_file = "pod-cp-%s.tgz" % str(uuid.uuid1())
    target_dir = os.path.dirname(target)
    target_file = os.path.basename(target)
    source_file = os.path.basename(source)
    if target_file == "":
        target_file = source_file
    try:
        if os.path.isdir(source):
            target += "/"
            cmd = ("GZIP=-1 tar -cpzf - -C " + source_dir + " " + source +
                   " | kubectl exec %s -i -- tee /tmp/" + tmp_tgz_file +
                   " >/dev/null") % pod
            if v:
                print(cmd)
            if os.system(cmd) != 0:
                raise
        else:
            cmd = ("GZIP=-1 tar --transform='flags=r;s|" + source_file + "|" +
                   target_file + "|' -czPf - -C " + source_dir + " " + source +
                   " | kubectl exec %s -i -- tee /tmp/" + tmp_tgz_file +
                   " >/dev/null") % pod
            if v:
                print(cmd)
            if os.system(cmd) != 0:
                raise

        # kill process if specified
        if kill is not None:
            cmd = "kubectl exec %s -- killall -9 %s 2>/dev/null" % (pod, kill)
            if v:
                print(cmd)
            os.system(cmd) != 0

        cmd = "kubectl exec %s -- tar zxf /tmp/%s -C %s" % (pod, tmp_tgz_file,
                                                            target_dir)
        if v:
            print(cmd)
        if os.system(cmd) != 0:
            raise
    except Exception as e:
        print e.__doc__
        print e.message
        sys.exit()
    finally:
        os.system("rm -f " + tmp_tgz_file)
        os.system("kubectl exec %s -- rm -f /tmp/%s 2>/dev/null" %
                  (env['GCE_CONF_BUCKET'], tmp_tgz_file))


parser = argparse.ArgumentParser(description='Copy files to POD')

parser.add_argument("-v", action='store_true', help="Show debug info")
parser.add_argument(
    "-k", "--kill", type=str, help="Kill process before copy to pod")

parser.add_argument("source", help="Source file or directory to copy")
parser.add_argument(
    "dest",
    help="Destination in format podname:/path/to.\
          Example: pod-id-aa12345:/path/to/dest/dir/")

args = parser.parse_args()

# print args
podPathPat = re.compile("^([^:]+):(.+)$")
podPath = podPathPat.match(args.dest)

if podPath is None:
    print "Invalid destination"
    sys.exit()
if os.path.exists(args.source) is False:
    print "Invalid source"
    sys.exit()

pod = subprocess.check_output(
    "kubectl get pod|grep " + podPath.group(1) +
    "|grep -v Terminating|cut -d' ' -f1",
    shell=True).rstrip()

cpFile(args.source, pod, podPath.group(2), args.kill, args.v)
