'''
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you 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 json
import os
from os.path import dirname
import pprint
import subprocess
import shutil

PROXY_VERIFIER_VERSION_FILENAME = 'proxy-verifier-version.txt'

test_root = dirname(dirname(AutestSitePath))
repo_root = dirname(test_root)

if Arguments.ats_bin is not None:
    # Add environment variables
    ENV['ATS_BIN'] = Arguments.ats_bin

if Arguments.build_root is not None:
    ENV['BUILD_ROOT'] = Arguments.build_root
else:
    # Assume the build root is the same directory tree as the test location.
    ENV['BUILD_ROOT'] = repo_root

host.WriteVerbose(['ats'], "Test build root: {}:".format(ENV['BUILD_ROOT']))

proxy_verifer_version_file = os.path.join(test_root, PROXY_VERIFIER_VERSION_FILENAME)
proxy_verifer_version = open(proxy_verifer_version_file, "rt").read().strip()

if Arguments.proxy_verifier_bin is not None:
    ENV['VERIFIER_BIN'] = Arguments.proxy_verifier_bin
    host.WriteVerbose(['ats'], "Expecting Proxy Verifier to be in user-supplied bin path: ", ENV['VERIFIER_BIN'])
else:
    # No Verifier bin path was specified. First see if a Proxy Verifier was
    # unpacked as a part of preparing for this test.
    unpack_bin = os.path.join(test_root, 'proxy-verifier', 'unpack', proxy_verifer_version, 'bin')
    if os.path.exists(os.path.join(unpack_bin, 'verifier-client')):
        ENV['VERIFIER_BIN'] = unpack_bin
        host.WriteVerbose(['ats'], "Using locally unpacked Proxy Verifier: ", ENV['VERIFIER_BIN'])
    else:
        # Finally check the PATH.
        path_search = shutil.which('verifier-client')
        if path_search is not None:
            ENV['VERIFIER_BIN'] = dirname(path_search)
            host.WriteVerbose(['ats'], "Using Proxy Verifier found in PATH: ", ENV['VERIFIER_BIN'])
        else:
            prepare_proxy_verifier_path = os.path.join(test_root, "prepare_proxy_verifier.sh")
            host.WriteError("Could not find Proxy Verifier binaries. "
                            "Try running: ", prepare_proxy_verifier_path)

required_pv_version = Version(proxy_verifer_version[1:])
verifier_client = os.path.join(ENV['VERIFIER_BIN'], 'verifier-client')
pv_version_out = subprocess.check_output([verifier_client, "--version"])
pv_version = Version(pv_version_out.decode("utf-8").split()[1])
if pv_version < required_pv_version:
    host.WriteError(
        f"Proxy Verifier at {verifier_client} is too old. "
        f"Version required: {required_pv_version}, version found: {pv_version}")
else:
    host.WriteVerbose(['ats'], f"Proxy Verifier at {verifier_client} has version: {pv_version}")

if ENV['ATS_BIN'] is not None:
    # Add variables for Tests
    traffic_layout = os.path.join(ENV['ATS_BIN'], "traffic_layout")
    tsxs = os.path.join(ENV['ATS_BIN'], "tsxs")
    if not os.path.isdir(ENV['ATS_BIN']):
        host.WriteError("--ats-bin requires a directory", show_stack=False)
    # setting up data from traffic_layout
    # this is getting layout structure
    if not os.path.isfile(traffic_layout):
        hint = ''
        if os.path.isfile(os.path.join(ENV['ATS_BIN'], 'bin', 'traffic_layout')):
            hint = "\nDid you mean '--ats-bin {}'?".\
                format(os.path.join(ENV['ATS_BIN'], 'bin'))
        host.WriteError("traffic_layout is not found. Aborting tests - Bad build or install.{}".format(hint), show_stack=False)
    try:
        out = subprocess.check_output([traffic_layout, "--json"])
    except subprocess.CalledProcessError:
        host.WriteError("traffic_layout is broken. Aborting tests - The build of traffic server is bad.", show_stack=False)
    out = json.loads(out.decode("utf-8"))
    for k, v in out.items():
        out[k] = v[:-1] if v.endswith('/') else v
    Variables.update(out)
    host.WriteVerbose(['ats'], "Traffic server layout Data:\n", pprint.pformat(out))
    # if the above worked this should as well
    # this gets feature data
    out = subprocess.check_output([traffic_layout, "--features", "--json"])
    out = json.loads(out.decode("utf-8"))
    Variables.update(out)
    host.WriteVerbose(['ats'], "Traffic server feature data:\n", pprint.pformat(out))

    # update version number
    out = subprocess.check_output([traffic_layout, "--version"])
    out = Version(out.decode("utf-8").split("-")[2].strip())
    Variables.trafficserver_version = out
    host.WriteVerbose(['ats'], "Traffic server version:", out)

    # this queries tsxs for build flags so we can build code for the tests and get certain
    # useful flags as which openssl to use when we don't use the system version
    out = {'CPPFLAGS': '', 'LIBS': '', 'LDFLAGS': '', 'CXX': ''}
    if os.path.isfile(tsxs):
        for flag in out.keys():
            try:
                data = subprocess.check_output([tsxs, "-q", flag])
                out[flag] = data.decode("utf-8")[:-1]
            except subprocess.CalledProcessError:
                # error if something goes wrong as the test will break if this exists and is broken
                host.WriteError("tsxs is broken. Aborting tests", show_stack=False)
    host.WriteVerbose(['ats'], "Traffic server build flags:\n", pprint.pformat(out))
    Variables.update(out)

Variables.AtsExampleDir = os.path.join(AutestSitePath, '..', '..', '..', 'example')
Variables.AtsTestToolsDir = os.path.join(AutestSitePath, '..', '..', 'tools')
Variables.VerifierBinPath = ENV['VERIFIER_BIN']
Variables.BuildRoot = ENV['BUILD_ROOT']
Variables.AtsTestPluginsDir = os.path.join(Variables.BuildRoot, 'tests', 'tools', 'plugins', '.libs')
Variables.AtsBuildGoldTestsDir = os.path.join(Variables.BuildRoot, 'tests', 'gold_tests')

# modify delay times as we always have to kill Trafficserver
# no need to wait
Variables.Autest.StopProcessLongDelaySeconds = 0
Variables.Autest.KillDelaySecond = 30
