#!/usr/bin/env python3
""""
 Copyright 2021-present Open Networking Foundation.

 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.

 Checks that the KPIMON CLI and the UENIB CLI return the same values for
 the average number of UEs
"""

import subprocess
import sys
import time

if __name__ == '__main__':
    failure = int(1)
    success = int(0)

    base_cli_command = 'kubectl -n micro-onos exec -t deploy/onos-cli -- onos '

    cli_command = base_cli_command
    checker = sys.argv[1]
    cli_args = sys.argv[2].split()

    for arg in cli_args[0:]:
        cli_command = cli_command + " " + arg

    checker_command = checker
    if len(sys.argv) > 3:
        checker_args = sys.argv[3].split()
        for arg in checker_args[0:]:
            checker_command = checker_command + " " + arg

    result = failure
    # capture CLI output
    max_attempts = int(15)
    done = False
    print("********* " + cli_command)
    while not done:
        try:
            print(cli_command)
            cli_output = subprocess.check_output(args=cli_command, shell=True)
            print("CLI output:\n" + cli_output.decode("utf-8"))

        except subprocess.CalledProcessError:
            cli_output = ""

        try:
            checker_output = subprocess.check_output(args=checker_command, input=cli_output, shell=True)
            print(checker_output.decode("utf-8"))
            exit(success)
        except subprocess.CalledProcessError as e:
            print("Checker error: " + e.output.decode("utf-8"))
            max_attempts -= 1

        if max_attempts == 0:
            done = True
            continue
        time.sleep(6)

    exit(failure)
