#    Copyright 2015 Mirantis, Inc.
#
#    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 proboscis import test
from proboscis import SkipTest

from fuelweb_test.settings import DEPLOYMENT_MODE
from fuelweb_test.settings import NEUTRON_SEGMENT
from fuelweb_test.tests.base_test_case import SetupEnvironment
from fuelweb_test.tests.base_test_case import TestBasic
from fuelweb_test.helpers.utils import run_on_remote


@test(groups=['fuel-mirror'])
class TestUseMirror(TestBasic):
    """Tests custom mirrors to deploy environment.

    Full documentation is in fuel-qa-docs in /doc folder of fuel-qa. It is
    autogenerated and can be found by keyword 'mirror'.

    This test doesn't only checks create mirror utility but also state of our
    mirrors. Most probable problem is absence of packet. It is possible that
    OS now requires new package for bootstrap, or puppet has new dependency
    that is not reflected in our mirror.
    """

    @test(groups=['fuel-mirror', 'use-mirror'],
          depends_on=[SetupEnvironment.prepare_slaves_5])
    def deploy_with_custom_mirror(self):
        """Create mirror for deployment without internet dependencies.

        TODO(akostrikov) wait for good way to package packetary/fuel-mirror.
        Good package covers steps from 1 to 7.

        Scenario:
            1. Install packages to build fuel-mirror and packetary
            2. Download packetary from github
            3. Checkout to packetary3 version of packetary
            4. Install packetary and fuel-mirror
            5. Create configuration directory
            6. Copy configuration file to configuration directory
            7. Update config file with real master ip.
            8. Run create mirror command
            9. Create cluster with neutron networking
            10. Add 3 nodes with controller role
            11. Add 1 node with compute role and 1 node with cinder role
            12. Run network verification
            13. Deploy the cluster
            14. Run OSTF
            15. Create snapshot

        Duration 90m
        Snapshot deploy_with_custom_mirror
        """
        self.env.revert_snapshot('ready_with_5_slaves')

        with self.env.d_env.get_admin_remote() as remote:
            # FIXME(akostrikov) This should be removed with correct install.
            # All that above is a hack.
            self.show_step(1, initialize=True)
            run_on_remote(remote,
                          'yum install git python-lxml.x86_64 '
                          'python-eventlet -y')
            self.show_step(2)
            run_on_remote(remote,
                          'cd /opt && rm -rf packetary && '
                          'git clone https://github.com/bgaifullin/packetary')
            self.show_step(3)
            run_on_remote(remote,
                          'cd /opt/packetary && git checkout packetary3')
            self.show_step(4)
            run_on_remote(remote, 'cd /opt/packetary && pip install -e .')
            run_on_remote(remote,
                          'cd /opt/packetary/contrib/fuel_mirror/ && '
                          'pip install -e .')
            self.show_step(5)
            run_on_remote(remote, 'mkdir -p /etc/fuel-mirror/')
            self.show_step(6)
            run_on_remote(remote,
                          'cp /opt/packetary/contrib/fuel_mirror/'
                          'etc/config.yaml /etc/fuel-mirror/config.yaml')
            self.show_step(7)
            admin_ip = str(
                self.env.d_env.nodes().admin.get_ip_address_by_network_name(
                    'admin'))
            cmd = "sed -r 's/{prev_ip}'/{admin_ip}/ -i'' {config_path}".format(
                prev_ip='10.20.0.2',
                admin_ip=admin_ip,
                config_path='/etc/fuel-mirror/config.yaml'
            )
            run_on_remote(remote, cmd)
            self.show_step(8)
            run_on_remote(remote, 'fuel-mirror create --ubuntu')

        self.show_step(9)

        cluster_id = self.fuel_web.create_cluster(
            name=self.__class__.__name__,
            mode=DEPLOYMENT_MODE,
            settings={
                "net_provider": 'neutron',
                "net_segment_type": NEUTRON_SEGMENT['tun'],
                'tenant': 'packetary',
                'user': 'packetary',
                'password': 'packetary'
            }
        )
        self.show_step(10)
        self.show_step(11)
        self.fuel_web.update_nodes(
            cluster_id,
            {
                'slave-01': ['controller'],
                'slave-02': ['controller'],
                'slave-03': ['controller'],
                'slave-04': ['compute'],
                'slave-05': ['cinder']
            }
        )
        self.show_step(12)
        self.fuel_web.verify_network(cluster_id)
        self.show_step(13)
        self.fuel_web.deploy_cluster_wait(cluster_id)

        self.show_step(14)
        self.fuel_web.run_ostf(
            cluster_id=cluster_id,
            test_sets=['ha', 'smoke', 'sanity'])

        self.env.make_snapshot('deploy_with_custom_mirror')

    @test(groups=['fuel-mirror', 'use-mirror'])
    def deploy_no_official_access(self):
        # TODO(akostrikov) add firewall rules to verify that there is no
        # connection to official mirrors during mirror creation and deployment.
        raise SkipTest('Not implemented yet')

    @test(groups=['fuel-mirror', 'use-mirror'])
    def deploy_with_proxy(self):
        # TODO(akostrikov) add tests to verify that fuel-mirror works with
        # proxies too.
        raise SkipTest('Not implemented yet')
