#! /usr/bin/python3
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.

# 'ovs-metrics' is a compatibility wrapper that launches 'ovs-watch' on the
# legacy dashboard.  Use 'ovs-watch' directly to access other dashboards.

import os
import shutil
import sys


# Options through which the user selects what to display.  When any is given,
# the default dashboard is not injected.
SELECTORS = (
    '-D', '--dashboard', '--columns',
    '--list-dashboards', '--list-columns',
)


def main() -> None:
    extra = sys.argv[1:]
    selected = any(
        arg in SELECTORS
        or arg.startswith('--dashboard=')
        or arg.startswith('--columns=')
        for arg in extra
    )
    if not selected:
        extra = ['--dashboard', 'legacy'] + extra

    same_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'ovs-watch')
    if os.path.isfile(same_dir) and os.access(same_dir, os.X_OK):
        target = same_dir
    else:
        target = shutil.which('ovs-watch')
    if target is None:
        sys.stderr.write("ovs-metrics: cannot find 'ovs-watch' to run\n")
        sys.exit(1)

    try:
        os.execv(target, [target] + extra)
    except OSError as e:
        sys.stderr.write("ovs-metrics: failed to run '%s': %s\n"
                         % (target, e.strerror))
        sys.exit(1)


if __name__ == '__main__':
    main()

# vi: filetype=python
