# Copyright 2018 Red Hat, 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.

import time

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException

testinfra_hosts = ['gitea99.opendev.org']


def test_gitea_listening(host):
    gitea_https = host.socket("tcp://0.0.0.0:3000")
    assert gitea_https.is_listening
    gitea_http = host.socket("tcp://0.0.0.0:3080")
    assert gitea_http.is_listening
    gitea_ssh = host.socket("tcp://0.0.0.0:222")
    assert gitea_ssh.is_listening
    gitea_proxy = host.socket("tcp://0.0.0.0:3081")
    assert gitea_proxy.is_listening

def test_ulimit(host):
    cmd = host.run("docker exec gitea-docker_gitea-web_1 prlimit")
    expected = ("STACK      max stack size                      "
                "16777216 9223372036854775807 bytes")
    assert expected in cmd.stdout.split('\n')

def test_robots(host):
    cmd = host.run('curl --insecure '
                   '--resolve gitea99.opendev.org:3081:127.0.0.1 '
                   'https://gitea99.opendev.org:3081/robots.txt')
    assert 'Disallow: /' in cmd.stdout

def test_matrix_server(host):
    cmd = host.run('curl --insecure -v '
                   '--resolve gitea99.opendev.org:3081:127.0.0.1 '
                   'https://gitea99.opendev.org:3081/.well-known/matrix/server')
    assert '"m.server": "opendev.ems.host:443"' in cmd.stdout
    assert 'Access-Control-Allow-Origin' not in cmd.stderr

def test_matrix_client(host):
    cmd = host.run('curl --insecure -v '
                   '--resolve gitea99.opendev.org:3081:127.0.0.1 '
                   'https://gitea99.opendev.org:3081/.well-known/matrix/client')
    assert '"base_url": "https://opendev.ems.host"' in cmd.stdout
    assert 'Access-Control-Allow-Origin' in cmd.stderr

def test_proxy(host):
    cmd = host.run('curl --insecure '
                   '--resolve gitea99.opendev.org:3081:127.0.0.1 '
                   'https://gitea99.opendev.org:3081/')
    assert 'Git with a cup of tea' in cmd.stdout

def test_proxy_ua_blacklist(host):
    cmd = host.run('curl --insecure -A '
                   '" Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)" '
                   '--resolve gitea99.opendev.org:3081:127.0.0.1 '
                   'https://gitea99.opendev.org:3081/')
    assert '403 Forbidden' in cmd.stdout

def test_ondisk_logs(host):
    mariadb_log = host.file('/var/log/containers/docker-mariadb.log')
    assert mariadb_log.exists

    gitea_log = host.file('/var/log/containers/docker-gitea.log')
    assert gitea_log.exists

    gitea_ssh_log = host.file('/var/log/containers/docker-gitea-ssh.log')
    assert gitea_ssh_log.exists
    assert gitea_ssh_log.contains("Server listening on :: port 222.")

def test_project_clone(host):
    # Note this tests the result of a project rename in gitea as well.
    cmd = host.run(
        'GIT_SSL_NO_VERIFY=1 '
        'git clone https://localhost:3081/opendev/disk-image-builder '
        '/tmp/disk-image-builder')
    assert "Cloning into '/tmp/disk-image-builder'..." in cmd.stderr
    assert cmd.succeeded

def test_gitea_screenshots(host):
        driver = webdriver.Remote(
        command_executor='http://%s:4444/wd/hub' % (host.backend.get_hostname()),
        desired_capabilities=webdriver.DesiredCapabilities.FIREFOX)

        shots = (
            ('https://localhost:3081', 'gitea-main.png'),
            ('https://localhost:3081/opendev/system-config',
             'gitea-project-system-config.png'),
            ('https://localhost:3081/opendev/disk-image-builder',
             'gitea-project-dib.png')
        )
        try:
            for url, png in shots:
                driver.get(url)
                WebDriverWait(driver, 30).until(
                    lambda driver: driver.execute_script(
                        'return document.readyState') == 'complete')
                time.sleep(5)
                # NOTE(ianw) This is a mash-up of things I found on
                # stackoverflow and other bits googling "full size
                # screenshot".  You expand the viewport and take a
                # shot of the <body> element so that you don't also
                # get scrollbars in the shot, with some tweaking
                # because the window size.  Apparently selinum 4
                # will have getFullPageScreeshotAs, so we should switch
                # to that when available.
                original_size = driver.get_window_size()
                required_width = driver.execute_script(
                    'return document.body.parentNode.scrollWidth')
                required_height = driver.execute_script(
                    'return document.body.parentNode.scrollHeight') + 100
                driver.set_window_size(required_width, required_height)

                driver.find_element_by_tag_name('body'). \
                    screenshot("/var/log/screenshots/%s" % png)

                driver.set_window_size(
                    original_size['width'], original_size['height'])

        except TimeoutException as e:
            raise e
        finally:
            driver.quit()