#!/usr/bin/env python

import os
import sys
import argparse

from yalibrary.yandex import sandbox
from yalibrary.yandex.sandbox import fetcher
import logging

_log = logging.getLogger(__name__)


def init_log(verbosity):
    log_level = logging.DEBUG if verbosity > 1 else logging.INFO if verbosity > 0 else logging.CRITICAL
    sb_log = logging.getLogger("sandbox.common.rest")
    sb_log.addHandler(logging.StreamHandler(sys.stderr))
    sb_log.setLevel(log_level)

    _log.addHandler(logging.StreamHandler(sys.stderr))
    _log.setLevel(log_level)


def rm_dir(path):
    if not os.path.exists(path):
        return
    for root, dirs, files in os.walk(path, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    os.rmdir(path)


def fetch_sandbox_resource(client, res_id, fname):
    rootdir = os.getcwd()
    tmpdir = os.path.join(rootdir, ".tmp")
    rm_dir(tmpdir)
    os.makedirs(tmpdir)

    display_name = fname if fname is not None else "(stdout)"
    _log.debug("Fetching sbr://%i as %s...", res_id, display_name)
    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"])

    tmp_name = os.path.join(tmpdir, resource_file_name)
    if fname is not None:
        _log.info("Fetched sbr://%i as %s", res_id, display_name)
        if os.path.isdir(fname):
            rm_dir(fname)
        if os.path.exists(fname):
            os.remove(fname)
        os.rename(tmp_name, fname)
        os.chmod(fname, 0775)
    else:
        with open(tmp_name, "r") as f:
            sys.stdout.write(f.read())
            os.remove(tmp_name)

if __name__ == "__main__":
    description = "Fetches binaries into a workcopy from sandbox"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('-v', help='Verbose mode', action='count', dest='verbosity', default=0)
    parser.add_argument('res_id', help='Sandbox resource id', type=int)
    parser.add_argument('output_file', help='Output file (optional)', nargs='?', type=str, default=None)

    args = parser.parse_args()
    init_log(args.verbosity)

    client = sandbox.SandboxClient()
    fetch_sandbox_resource(client, args.res_id, args.output_file)
