#!/usr/bin/env python3
# Copyright 2017-2018 The Wazo Authors  (see the AUTHORS file)
# SPDX-License-Identifier: GPL-3.0+

import logging
import urllib3

from xivo_auth_client import Client as AuthClient
from wazo_plugind_client import Client as PlugindClient
from xivo.config_helper import parse_config_file
from xivo.xivo_logging import silence_loggers

PLUGIND_CLI_KEY = '/var/lib/xivo-auth-keys/wazo-plugind-cli-key.yml'
logger = logging.getLogger('upgrade_admin_ui_official_plugins')
logging.basicConfig(level=logging.INFO)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def auth_config():
    key_file = parse_config_file(PLUGIND_CLI_KEY)
    return {'host': 'localhost',
            'username': key_file['service_id'],
            'password': key_file['service_key'],
            'verify_certificate': False}


def plugind_config():
    return {'host': 'localhost',
            'verify_certificate': False}


def main():
    auth_client = AuthClient(**auth_config())
    token_data = auth_client.token.new('xivo_service', expiration=300)

    plugind_client = PlugindClient(**plugind_config())
    plugind_client.set_token(token_data['token'])

    plugin_list = plugind_client.market.list(namespace='official', installed=True)
    for plugin in plugin_list['items']:
        for version in plugin['versions']:
            if version['upgradable'] is True:
                logger.info('Upgrading plugin %s ...', plugin['name'])
                plugind_client.plugins.install(method='market',
                                               options={'namespace': 'official',
                                                        'name': plugin['name'],
                                                        'version': version['version']})
                break


if __name__ == '__main__':
    main()
