#!/usr/bin/env python

import os
import sys
import argparse
import yaml
import shutil

from datetime import datetime

def fix_sys_path():
    # suppress fleur logging
    from logging import NullHandler, getLogger
    getLogger("devtools.fleur.imports.path").addHandler(NullHandler())
    # Access arcadia source tree
    import arcadia # if not found: see https://nda.ya.ru/3Tknpm
    from devtools.fleur.imports.arcadiahook import GetArcadiaPath
    sys.path.insert(0, os.path.join(GetArcadiaPath(), "devtools", "ya"))
    arcadia.use()
fix_sys_path()

from devtools.ya.test.dependency import parse_sandbox_uri
#from devtools.ya.test.sandbox_storage import SandboxStorage
from yalibrary.yandex import sandbox
from yalibrary.yandex.sandbox import fetcher

def soft_rm_dir(path):
    if os.path.isdir(path):
        for f in os.listdir(path):
            os.remove(os.path.join(path, f))
        os.rmdir(path)


def make_wc_path(target_prefix):
    suffix = ""
    idx = 1;
    date = datetime.now()
    while True:
        path = "{}{:%Y%m%d}{}".format(target_prefix, date, suffix)
        if not os.path.isdir(path) or not os.path.isfile(os.path.join(path,".uploaded")):
            break;
        suffix = "_{}".format(idx)
        idx = idx+1

#    if os.path.isdir(path):
#        for f in os.listdir(path):
#            os.remove(os.path.join(path, f))
#        os.rmdir(path)

    if not os.path.isdir(path):
        os.makedirs(path)
    return path;

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", dest="config", default="config.yaml", help="config file to use")
    parser.add_argument("--target", help="target dir override")
    parser.add_argument("--target-prefix", default="loadtest", help="target prefix override (default: loadtest)")

    args = parser.parse_args()
    config_file = args.config

    target = args.target or make_wc_path(args.target_prefix)
    print >> sys.stderr, "Preparing new workcopy at {}".format(target)

    with open(config_file, "r") as config_stream:
        config = yaml.load(config_stream)


    rootdir = os.getcwd()
    tmpdir = os.path.join(rootdir,".tmp")
    soft_rm_dir(tmpdir)
    os.makedirs(tmpdir)
    os.chdir(target)

    client = sandbox.SandboxClient();

    for kv in config['binaries'].iteritems():
        fname = kv[0]
        if os.path.isfile(fname):
            os.remove(fname)
        uri = kv[1]
        sys.stderr.write("Saving {} as {}...".format(uri, fname))
        res_id = parse_sandbox_uri(uri)
        res_info = client.get_resource(res_id)
        resource_file_name = os.path.basename(res_info["file_name"])

        fetcher.download_resource(res_id, tmpdir, ["skynet", "http"])
        sys.stderr.write("Done" + os.linesep)
        os.rename(os.path.join(tmpdir, resource_file_name), fname)
        os.chmod(fname, 0775)

    os.chdir(rootdir)

    template_name = config['wc_template']
    shutil.copy(os.path.join(rootdir, "static", "{}.yaml".format(template_name)), target + ".yaml")

    template_dir = os.path.join(rootdir, "static", template_name)
    sys.stderr.write("Adding files from '{}' to workcopy...".format(template_name))
    for fname in os.listdir(template_dir): # not copytree, because of .svn and other stuff
        src = os.path.join(template_dir, fname)
        dst = os.path.join(target, fname)
        shutil.copy(src, dst)
        shutil.copystat(src, dst)
    sys.stderr.write("Done" + os.linesep)
    sys.stderr.write("\x1B[92mNow edit " + target + ".yaml to set your mmeta groups\x1B[0m"  + os.linesep)


