#!/usr/bin/python3
#
# Copyright (C) 2020-2023 NVIDIA Corporation. ALL RIGHTS RESERVED.
# Copyright (C) 2017,2018 Cumulus Networks, Inc. all rights reserved
#
# This software is subject to the Cumulus Networks End User License
# Agreement available at the following locations:
#
# Internet: https://cumulusnetworks.com/downloads/eula/latest/view/
# Cumulus Linux systems: /usr/share/cumulus/EULA.txt
#
# validate-ports --
#
#     Validate a ports.conf file (/etc/cumulus/ports.conf by default) for
#     correctness.
#
import os
import sys
import argparse
import subprocess

import cumulus.portvalidator

class ArgParseError(RuntimeError):
    pass

def _run_validate_portsconf(args):
    # validate ports.conf runs on ports.conf, if custom file specified
    # need to copy custom file to /tmp/validate_ports.conf, and remove it 
    # after validation

    if args.file != '/etc/cumulus/ports.conf':
        custom_file = True
    else:
        custom_file = False

    if custom_file:
        if not os.path.exists(args.file):
            print('src file not found')
            return -1

        copy_cmd = 'cp -f ' + args.file + ' /tmp/validate_ports.conf '
#        print copy_cmd
        try:
            output = subprocess.check_output(copy_cmd, shell=True, stderr=subprocess.STDOUT)
            print(output)
        except subprocess.CalledProcessError as e:
            print(("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)))
            print('copy ports.conf CPE failing ')
            print(output)
            print(e)
            return -1
        except Exception as e:
            print('copy ports.conf exception failing ')
            print(e)
            return -1

    validate_cmd='/usr/lib/cumulus/update-ports -f -s'
    try:
        output = subprocess.check_output(validate_cmd, shell=True, stderr=subprocess.STDOUT)
        if output:
            print('update-ports returned output: ')
            print(output)
        else:
            print('update-ports returned ')
        valid = True
    except subprocess.CalledProcessError as e:
        print(("update-ports returned with error (code {}): {}".format(e.returncode, e.output)))
        valid = False
    except Exception as e:
        print(("update-ports exception '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)))
        print(e)
        valid = False

    if custom_file:
        remove_cmd = 'rm -f /tmp/validate_ports.conf'
        try:
            output = subprocess.check_output(remove_cmd, shell=True, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            print(("remove command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)))
        except Exception as e:
            print('remove-cmd exception ')
            print(e)

    if (valid):
        return 0
    else:
        print('ports configuration(ports.conf/ports_width.conf) is invalid')
        return -1

# ---------------------------------------------------------
#
#                         m a i n
#
# ----------------------------------------------------------

def main(argv) :
    parser = argparse.ArgumentParser(
        description='Validate Cumulus ports.conf configuration')
    parser.add_argument('-f', '--file',
                        dest="file",
                        required=False,
                        action='store',
                        help='Supply alternate path for ports.conf.',
                        default="/etc/cumulus/ports.conf")
    parser.add_argument('-d', '--debug',
                        required=False,
                        action='store_true',
                        help=argparse.SUPPRESS,
                        default=False)

    try:
        args = parser.parse_args()
    except ArgParseError as e:
        parser.error(str(e))
        exit(-1)

    status = _run_validate_portsconf(args)
    if status == 0:
        print('ports validation passed')
    else:
        #print 'Error: ports validation failed'
        exit(1)

    pv = cumulus.portvalidator.Portvalidator(args.file, args.debug)
    retlist = pv.portvalidator()

    if len(retlist) > 0:
        pv.portwriteerrors(retlist)

    exit(len(retlist) > 0)

# ----------------------------------------------------------
#
#                         e n t r y
#
# ----------------------------------------------------------
if __name__ == "__main__":
    main(sys.argv[1:])
