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

import requests
import logging
import os


class NannyVault(object):
    NANNY_VAULT_URL = 'https://nanny-vault.yandex-team.ru/v1'
    CRT_PATH = '/usr/local/share/ca-certificates/YandexInternalRootCA.crt'

    def __init__(self, oauth_token):
        self.__oauth_token = oauth_token
        self.__keychain_data = {}
        # Prepare connection
        self._verify = False if not os.path.isfile(self.CRT_PATH) else self.CRT_PATH
        self.__connection = requests.Session()
        self._create_connection()

    def _create_connection(self):
        session = requests.Session()
        resp = session.post('%s/auth/blackbox/login/keychain' % self.NANNY_VAULT_URL,
                            json={'oauth': self.__oauth_token}, verify=self._verify)
        if not resp.ok:
            logging.error(resp.text)
        resp.raise_for_status()
        self.__keychain_data = resp.json()['data']
        session.headers['X-Vault-Token'] = resp.json()['auth']['client_token']
        self.__connection = session

    def get_keychains_list(self):
        keychains = []
        for kc in self.__keychain_data['keychains']:
            keychains.append(kc['id'])
        return keychains

    def get_keychain_info(self, keychain):
        for kc in self.__keychain_data['keychains']:
            if keychain == kc['id']:
                return kc

    def add_service_to_keychain(self, keychain, service):
        request_url = '%s/auth/blackbox/keychain/%s' % (self.NANNY_VAULT_URL, keychain)
        resp = self.__connection.get(request_url)

        if resp.status_code != 200:
            logging.error('[%s]Cannot get keychain info. Check keychain, permissions or renew connection', keychain)
            return
        keychain_data = resp.json()['data']

        # Check for service exists
        for sr in keychain_data['services']:
            if service == sr['id']:
                logging.error('Service %s already exists in keychain %s', service, keychain)
                return

        keychain_data['services'].append({u'id': service})
        resp = self.__connection.put(request_url, json=keychain_data)
        if resp.status_code == 204:
            logging.info('Adding service %s to keychain %s SUCCESS', service, keychain)

    def get_secret_revisions(self, keychain, secret):
        request_url = '%s/secret/%s/%s?list=true' % (self.NANNY_VAULT_URL, keychain, secret)
        resp = self.__connection.get(request_url)
        if resp.status_code != 200:
            logging.error('[%s]Cannot get keychain secret revisions. Check keychain, permissions or renew connection',
                          keychain)
            return
        return resp.json()['data']['keys']

    def get_secrets_list(self, keychain):
        request_url = '%s/secret/%s?list=true' % (self.NANNY_VAULT_URL, keychain)
        resp = self.__connection.get(request_url)
        if resp.status_code != 200:
            logging.error('[%s]Cannot get keychain secrets. Check keychain, permissions or renew connection',
                          keychain)
            return
        return resp.json()['data']['keys']
