#!/usr/bin/python2.7

# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
#
#    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.

import glob
import os
from subprocess import check_call, Popen, PIPE
import sys
import traceback

import smf_include

from openstack_common import alter_mysql_tables, create_backups, modify_conf


NEUTRON_CONF_MAPPINGS = {
    # Deprecated group/name for Liberty
    ('DEFAULT', 'use_syslog'): (None, None),
    ('DEFAULT', 'log_format'): (None, None),
    ('DEFAULT', 'rpc_thread_pool_size'):
        ('DEFAULT', 'executor_thread_pool_size'),
    ('DEFAULT', 'nova_region_name'): ('nova', 'region_name'),
    ('DEFAULT', 'nova_admin_username'): ('nova', 'username'),
    ('DEFAULT', 'nova_admin_tenant_id'): ('nova', 'tenant_id'),
    ('DEFAULT', 'nova_admin_tenant_name'): ('nova', 'tenant_name'),
    ('DEFAULT', 'nova_admin_password'): ('nova', 'password'),
    ('DEFAULT', 'nova_admin_auth_url'): ('nova', 'auth_url'),
}

NEUTRON_CONF_EXCEPTIONS = [
    ('database', 'connection'),
    ('keystone_authtoken', 'auth_uri'),
    ('keystone_authtoken', 'identity_uri'),
    ('keystone_authtoken', 'admin_tenant_name'),
    ('keystone_authtoken', 'admin_user'),
    ('keystone_authtoken', 'admin_password'),
    ('keystone_authtoken', 'signing_dir'),
    # Do not overwrite EVS options with OVS options since upgrade
    # doesn't handle EVS to OVS upgrade
    ('DEFAULT', 'core_plugin'),
    ('DEFAULT', 'service_plugins'),
    ('nova', 'username'),
    ('nova', 'tenant_name'),
    ('nova', 'password'),
    ('nova', 'auth_url'),
]

L3_AGENT_MAPPINGS = {
    ('DEFAULT', 'evs_controller'): (None, None),
    ('DEFAULT', 'external_network_datalink'): (None, None),
}

L3_AGENT_EXCEPTIONS = [
    ('DEFAULT', 'ovs_integration_bridge'),
    ('DEFAULT', 'interface_driver'),
    ('DEFAULT', 'external_network_bridge'),
    ('DEFAULT', 'auth_url'),
]

DHCP_AGENT_MAPPINGS = {
    ('DEFAULT', 'evs_controller'): (None, None)
}

DHCP_AGENT_EXCEPTIONS = [
    ('DEFAULT', 'ovs_integration_bridge'),
    ('DEFAULT', 'interface_driver'),
]

METADATA_AGENT_EXCEPTIONS = [
    ('DEFAULT', 'auth_url'),
    ('DEFAULT', 'auth_region'),
    ('DEFAULT', 'admin_tenant_name'),
    ('DEFAULT', 'admin_user'),
    ('DEFAULT', 'admin_password'),
    ('DEFAULT', 'metadata_workers'),
]

OPENVSWITCH_AGENT_EXCEPTIONS = [
    ('ovs', 'integration_bridge'),
    ('ovs', 'tunnel_bridge'),
    ('securitygroup', 'enable_security_group'),
    ('securitygroup', 'enable_ipset'),
]

ML2_CONF_MAPPINGS = {
    ('ml2', 'segment_mtu'): ('DEFAULT', 'global_physnet_mtu'),
}

ML2_CONF_EXCEPTIONS = [
    ('ml2', 'type_drivers'),
    ('ml2', 'tenant_network_types'),
    ('ml2', 'mechanism_drivers'),
    ('securitygroup', 'enable_security_group'),
    ('securitygroup', 'enable_ipset'),
]


def start():
    # pull out the current version of config/upgrade-id
    p = Popen(['/usr/bin/svcprop', '-p', 'config/upgrade-id',
               os.environ['SMF_FMRI']], stdout=PIPE, stderr=PIPE)
    curr_ver, _err = p.communicate()
    curr_ver = curr_ver.strip()

    # extract the openstack-upgrade-id from the pkg
    p = Popen(['/usr/bin/pkg', 'contents', '-H', '-t', 'set', '-o', 'value',
               '-a', 'name=openstack.upgrade-id',
               'pkg:/cloud/openstack/neutron'], stdout=PIPE, stderr=PIPE)
    pkg_ver, _err = p.communicate()
    pkg_ver = pkg_ver.strip()

    if curr_ver == pkg_ver:
        # No need to upgrade
        sys.exit(smf_include.SMF_EXIT_OK)

    # TODO: Kilo EVS check. If upgrade is from Kilo running EVS,
    # fail the upgrade.

    # look for any .new files
    if glob.glob('/etc/neutron/*.new'):
        # the versions are different, so perform an upgrade
        # modify the configuration files

        # backup all the old configuration files
        create_backups('/etc/neutron')

        modify_conf('/etc/neutron/api-paste.ini')
        modify_conf('/etc/neutron/dhcp_agent.ini', mapping=DHCP_AGENT_MAPPINGS,
                    exception_list=DHCP_AGENT_EXCEPTIONS)
        modify_conf('/etc/neutron/l3_agent.ini', mapping=L3_AGENT_MAPPINGS,
                    exception_list=L3_AGENT_EXCEPTIONS)
        modify_conf('/etc/neutron/neutron.conf', mapping=NEUTRON_CONF_MAPPINGS,
                    exception_list=NEUTRON_CONF_EXCEPTIONS)
        modify_conf('/etc/neutron/metadata_agent.ini', mapping=None,
                    exception_list=METADATA_AGENT_EXCEPTIONS)

    # look for any .new files for ml2 plugin
    if glob.glob('/etc/neutron/plugins/ml2/*.new'):
        # modify the configuration files
        # backup all the old configuration files
        create_backups('/etc/neutron/plugins/ml2')

        modify_conf('/etc/neutron/plugins/ml2/openvswitch_agent.ini',
                    mapping=None,
                    exception_list=OPENVSWITCH_AGENT_EXCEPTIONS)

        modify_conf('/etc/neutron/plugins/ml2/ml2_conf.ini',
                    mapping=ML2_CONF_MAPPINGS,
                    exception_list=ML2_CONF_EXCEPTIONS)

    # update the current version
    check_call(['/usr/sbin/svccfg', '-s', os.environ['SMF_FMRI'], 'setprop',
               'config/upgrade-id', '=', pkg_ver])
    check_call(['/usr/sbin/svccfg', '-s', os.environ['SMF_FMRI'], 'refresh'])

    sys.exit(smf_include.SMF_EXIT_OK)


if __name__ == '__main__':
    os.putenv('LC_ALL', 'C')
    try:
        smf_include.smf_main()
    except RuntimeError:
        sys.exit(smf_include.SMF_EXIT_ERR_FATAL)
    except Exception as err:
        print 'Unknown error:  %s' % err
        print
        traceback.print_exc(file=sys.stdout)
        sys.exit(smf_include.SMF_EXIT_ERR_FATAL)
