#!/usr/bin/python3

# Copyright (c) 2019, SUSE LLC, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library.

"""URL Resolver zypper plugin. This plugin resolves the url to the proper
   update server and sends along the necessary instance data."""


import base64
import logging

import cloudregister.registerutils as utils

from zypp_plugin import Plugin

utils.start_logging()
utils.set_proxy()


class SUSECloudPlugin(Plugin):
    def RESOLVEURL(self, headers, body):
        """Convert the URL for the repo"""
        update_server = utils.get_smt()
        server_name = ''
        if not update_server:
            # Something went seriously wrong, however try the name from
            # the hosts file
            server_name = utils.get_update_server_name_from_hosts()
        else:
            server_name = update_server.get_FQDN()
        if server_name:
            srv_url = 'https://%s' % server_name
            repo_url = srv_url + headers.get('path')
            credentials = headers.get('credentials')
            if credentials:
                repo_url += '?credentials=' + credentials
            instance_data = bytes(
                utils.get_instance_data(utils.get_config()),
                'utf-8'
            )
            # zypper wants a string or bad things happen on the other side
            inst_data_bin_str = base64.b64encode(instance_data).decode('utf-8')
        else:
            repo_url = None
        self.answer(
            'RESOLVEDURL',
            {'X-Instance-Data': inst_data_bin_str},
            repo_url
        )


plugin = SUSECloudPlugin()
plugin.main()
