#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
sys.path.insert(0, '/opt/direct-py/startrek-python-client-sni-fix')

import os
import requests
import json

from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

TOKENS = '/etc/direct-tokens/twilight/.env'
SANDBOX_API='https://sandbox.yandex-team.ru/api/v1.0'


def dotenv(path):
    with open(path, 'r') as fh:
        vars_dict = dict(
            tuple(item.strip('"\n') for item in line.split('='))
            for line in fh.readlines() if not line.startswith('#')
        )
    os.environ.update(vars_dict)

# первым шагом можно попробовать добавить arcadia:/robots/trunk/genconf/PORTOVM/common/apt-update.sh
# если будут проблемы

scripts='''arcadia:/arc/trunk/arcadia/adv/frontend/portovm/base/set_sources_list.sh
arcadia:/robots/trunk/genconf/PORTOVM/common/apt-update.sh
arcadia:/arc/trunk/arcadia/adv/frontend/portovm/base/install.sh
arcadia:/arc/trunk/arcadia/adv/frontend/portovm/base/prepare_environment.sh'''


def main():
    dotenv(TOKENS)

    r = requests.post('%s/task' % SANDBOX_API, \
        headers = {
            'Authorization': 'OAuth %s' % os.environ['SANDBOX_OAUTH_TOKEN'],
            'Content-Type': 'application/json'
        },
        data = json.dumps({
            'type': 'BUILD_PORTO_LAYER',
            'description': 'qemu image for direct DNA development',
            'tags': [
                'DIRECT_FRONTEND',
                'QEMU_IMAGE'
            ],
            'kill_timeout': 60 * 60, # 1 час
            'priority': {
                'class': 'BACKGROUND',
                'subclass': 'HIGH'
            },
            'important': True,
            'owner': 'DIRECT',
            'notifications': [],
            'custom_fields': [
                {
                    'name': 'parent_layer_type',
                    'value': 'PORTO_LAYER_SEARCH_UBUNTU_XENIAL_QEMU'
                },
                {
                    'name': 'layer_type',
                    'value': 'QEMU_IMAGE_SEARCH_XENIAL_DEVEL'
                },
                {
                    'name': 'layer_name',
                    'value': 'layer'
                },
                {
                    'name': 'merge_layers',
                    'value': True
                },
                {
                    'name': 'compress',
                    'value': 'tar.xz'
                },
                {
                    'name': 'script',
                    'value': scripts
                },
                {
                    'name': 'script2',
                    'value': 'arcadia:/robots/trunk/genconf/PORTOVM/common/cleanup.sh'
                },
                {
                    'name': 'script_env',
                    'value': {
                        'virt_mode': 'qemu'
                    }
                },
                {
                    'name': 'start_os',
                    'value': True
                },
                {
                    'name': 'output_resource_attr',
                    'value': {
                         'ttl': 'inf'
                    }
                }
            ]
        }),
        verify = False
    )

    if r.status_code == 201:
        job = r.json()
        start = requests.put('%s/batch/tasks/start' % SANDBOX_API, \
            headers = {
                'Authorization': 'OAuth %s' % os.environ['SANDBOX_OAUTH_TOKEN'],
                'Content-Type': 'application/json'
            },
            data = json.dumps([
                job['id']
            ]),
            verify = False
        )

        print start.status_code
        print 'https://sandbox.yandex-team.ru/task/%s' % job['id']

    else:
        print 'failed to start'
        print r.status_code
        print r.json()


if __name__ == '__main__':
    main()
