#!/usr/bin/python
# Copyright 2017 Northern.tech AS
#
#    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
#
#        https://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 fabric.api import *
import pytest
import subprocess
import tempfile
import time
import conftest
from common import *

COMPOSE_FILES = [
    "../docker-compose.yml",
    "../docker-compose.client.yml",
    "../docker-compose.storage.minio.yml",
    "../docker-compose.testing.yml"
]

log_files = []


def docker_compose_cmd(arg_list, use_common_files=True):
    extra_files = conftest.extra_files
    if extra_files is None:
        extra_files = []

    files_args = ""

    if use_common_files:
        for file in COMPOSE_FILES + extra_files:
            files_args += " -f %s" % file

    with conftest.docker_lock:
        cmd = "docker-compose -p %s %s %s" % (conftest.docker_compose_instance,
                                              files_args,
                                              arg_list)

        logging.info("running with: %s" % cmd)

        try:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        except subprocess.CalledProcessError as e:
            print "failed to start docker-compose (called: %s): exit code: %d, output: %s" % (e.cmd, e.returncode, e.output)

def stop_docker_compose():
    # take down all COMPOSE_FILES and the s3 specific files
    docker_compose_cmd(" -f ../docker-compose.storage.s3.yml -f ../extra/travis-testing/s3.yml down -v")
    set_setup_type(None)


def start_docker_compose(clients=1):
    inline_logs = conftest.inline_logs

    docker_compose_cmd("up -d")
    if clients > 1:
        docker_compose_cmd("scale mender-client=%d" % clients)

    if inline_logs:
        docker_compose_cmd("logs -f &")
    else:
        tfile = tempfile.mktemp("mender_testing")
        docker_compose_cmd("logs -f --no-color > %s 2>&1 &" % tfile)
        logging.info("docker-compose log file stored here: %s" % tfile)
        log_files.append(tfile)

    ssh_is_opened()

    set_setup_type(ST_OneClient)


def restart_docker_compose(clients=1):
    stop_docker_compose()
    start_docker_compose(clients)


def docker_get_ip_of(image):
    # Returns newline separated list of IPs
    output = subprocess.check_output("docker ps | grep '%s' | grep '%s'| awk '{print $1}'| xargs -r docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'" % (conftest.docker_compose_instance, image), shell=True)

    # Return as list.
    return output.split()


def get_mender_clients():
    return [ip + ":8822" for ip in docker_get_ip_of("mendersoftware/mender-client-qemu")]


def get_mender_gateway():
    gateway = docker_get_ip_of("mendersoftware/api-gateway")

    if len(gateway) != 1:
        raise SystemExit("more then one api-gateway running, which is unexpected")

    return gateway[0]

def ssh_is_opened():
    execute(ssh_is_opened_impl, hosts=get_mender_clients())


@parallel
def ssh_is_opened_impl(cmd="true", wait=60):
    count = 0

    while count < wait:
        try:
            # no point in printing this with each test
            with quiet():
                return run(cmd)
        except BaseException:
            time.sleep(1)
            count += 1
            continue
        else:
            break

    if count >= 60:
        logging.fail("Unable to connect to host: ", env.host_string)

@@ -2643,20 +2643,22 @@
 _of(
-imag
+servic
 e):%0A    
 # Re
@@ -2657,148 +2657,535 @@
     
-# 
+%22%22%22
 Return
-s newline separated list of IPs%0A    output = subprocess.check_output(%22docker ps %7C grep '%25s' %7C grep '%25s'%7C awk '%7Bprint $1%7D'%7C xargs -r 
+ a list of IP addresseses of %60service%60. %60service%60 is the same name as%0A    present in docker-compose files.%0A    %22%22%22%0A    temp = %22docker ps -q %22 %5C%0A           %22--filter label=com.docker.compose.project=%7Bproject%7D %22 %5C%0A           %22--filter label=com.docker.compose.service=%7Bservice%7D %22%0A    cmd = temp.format(project=conftest.docker_compose_instance,%0A                      service=service)%0A%0A    output = subprocess.check_output(cmd + %5C%0A                                     %22%7C xargs -r %22 %5C%0A                                     %22
 dock
@@ -3267,53 +3267,46 @@
 %7D%7D'%22
- %25 (conftest.docker_compose_instance, image),
+,%0A                                    
  she
@@ -3444,31 +3444,16 @@
 _ip_of(%22
-mendersoftware/
 mender-c
@@ -3461,13 +3461,8 @@
 ient
--qemu
 %22)%5D%0A
@@ -3531,17 +3531,9 @@
 nder
-software/
+-
 api-

use compose file service name and label instead of image name when looking up services