# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import uuidutils

from sahara import conductor as cond
from sahara import context
from sahara import exceptions as exc
from sahara.i18n import _
from sahara.plugins import provisioning as base
from sahara.plugins import utils as pl_utils
from sahara.service.castellan import utils as key_manager
from sahara.utils import cluster as cl_utils
from sahara.utils import cluster_progress_ops as cpo
from sahara.utils import files


conductor = cond.API
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
POLICY_FILES_DIR = '/tmp/UnlimitedPolicy'


class KDCInstallationFailed(exc.SaharaException):
    code = 'KDC_INSTALL_FAILED'
    message_template = _('KDC installation failed by reason: {reason}')

    def __init__(self, reason):
        message = self.message_template.format(reason=reason)
        super(KDCInstallationFailed, self).__init__(message)


def _config(**kwargs):
    return base.Config(
        applicable_target='Kerberos', priority=1,
        is_optional=True, scope='cluster', **kwargs)


enable_kerberos = _config(
    name='Enable Kerberos Security', config_type='bool',
    default_value=False)
use_existing_kdc = _config(
    name='Existing KDC', config_type='bool',
    default_value=False)
kdc_server_ip = _config(
    name='Server IP of KDC', config_type='string',
    default_value='192.168.0.1',
    description=_('Server IP of KDC server when using existing KDC'))
realm_name = _config(
    name='Realm Name', config_type='string',
    default_value='SAHARA-KDC',
    description=_('The name of realm to be used'))
admin_principal = _config(
    name='Admin principal', config_type='string',
    default_value='sahara/admin',
    description=_('Admin principal for existing KDC server'))
admin_password = _config(
    name='Admin password', config_type='string', default_value='')
policy_url = _config(
    name="JCE libraries", config_type='string',
    default_value=('https://tarballs.openstack.org/sahara-extra/dist/'
                   'common-artifacts/'),
    description=_('Java Cryptography Extension (JCE) '
                  'Unlimited Strength Jurisdiction Policy Files location')
)


def get_config_list():
    return [
        enable_kerberos,
        use_existing_kdc,
        kdc_server_ip,
        realm_name,
        admin_principal,
        admin_password,
        policy_url,
    ]


def get_kdc_host(cluster, server):
    if using_existing_kdc(cluster):
        return "server.%s" % CONF.node_domain
    return server.fqdn()


def is_kerberos_security_enabled(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=enable_kerberos)


def using_existing_kdc(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=use_existing_kdc)


def get_kdc_server_ip(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=kdc_server_ip)


def get_realm_name(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=realm_name)


def get_admin_principal(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=admin_principal)


def get_admin_password(cluster):
    # TODO(vgridnev): support in follow-up improved secret storage for
    # configs
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=admin_password)


def get_policy_url(cluster):
    return pl_utils.get_config_value_or_default(
        cluster=cluster, config=policy_url)


def setup_clients(cluster, server=None, instances=None):
    if not instances:
        instances = cl_utils.get_instances(cluster)
    server_ip = None
    cpo.add_provisioning_step(
        cluster.id, _("Setting Up Kerberos clients"), len(instances))

    if not server:
        server_ip = get_kdc_server_ip(cluster)
    with context.ThreadGroup() as tg:
        for instance in instances:
            tg.spawn('setup-client-%s' % instance.instance_name,
                     _setup_client_node, cluster, instance,
                     server, server_ip)


def prepare_policy_files(cluster, instances=None):
    if instances is None:
        instances = pl_utils.get_instances(cluster)

    remote_url = get_policy_url(cluster)
    cpo.add_provisioning_step(
        cluster.id, _("Preparing policy files"), len(instances))
    with context.ThreadGroup() as tg:
        for inst in instances:
            tg.spawn(
                'policy-files',
                _prepare_policy_files, inst, remote_url)


def deploy_infrastructure(cluster, server=None):
    if not is_kerberos_security_enabled(cluster):
        LOG.debug("Kerberos security disabled for cluster")
        return
    if not using_existing_kdc(cluster):
        deploy_kdc_server(cluster, server)

    setup_clients(cluster, server)


def _execute_script(client, script):
    with client.remote() as remote:
        script_path = '/tmp/%s' % uuidutils.generate_uuid()[:8]
        remote.write_file_to(script_path, script)
        remote.execute_command('chmod +x %s' % script_path)
        remote.execute_command('bash %s' % script_path)
        remote.execute_command('rm -rf %s' % script_path)