#!python
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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 argparse
import os
import sys

import click

from rucio.cli.bin_legacy.rucio import get_parser
from rucio.cli.command import main
from rucio.common.config import clean_cached_config, config_get, config_get_list
from rucio.common.utils import setup_logger


def run_command(args, use_multi_host_functionality):
    commands = ("account", "config", "did", "replica", "rse", "rule", "scope", "subscription", "ping", "whoami", "lifetime-exception", "upload", "download", "opendata", "data")
    if (any(arg in commands for arg in sys.argv)) or args.help or args.version:
        main(standalone_mode=not use_multi_host_functionality)  # pylint: disable=E1120

    else:
        try:
            get_parser().parse_args()
            msg = "This method is deprecated. Please view rucio -h for an updated help menu"
            logger.error(msg)
            sys.exit(1)
        # Make a custom warning - show the new help menu when invalid commands are called.
        except argparse.ArgumentError:
            logger.error("Invalid argument(s) - %s " % sys.argv[1:])
            with click.Context(main) as ctx:
                print(main.get_help(ctx))
            sys.exit(1)


if __name__ == "__main__":

    parser = argparse.ArgumentParser(add_help=False)
    # Check for commands in the new command list
    parser.add_argument("-h", "--help", action="store_true")
    parser.add_argument("--version", action="store_true")

    args, _ = parser.parse_known_args()

    logger = setup_logger(module_name=__name__)

    multi_host_commands = config_get('client', 'multi_host_commands', raise_exception=False, default='')
    use_multi_host = False
    if "--config" not in sys.argv:
        for arg in sys.argv:
            if arg in [x.strip() for x in multi_host_commands.split(',')]:
                use_multi_host = True

    if use_multi_host:
        multi_host_servers = config_get_list('client', 'multi_host_servers')
        for host in multi_host_servers:
            config = config_get(host, 'config_file')
            clean_cached_config()
            os.environ['RUCIO_CONFIG'] = config
            print('Result from {}.'.format(host))

            run_command(args, use_multi_host)
    else:
        run_command(args, use_multi_host)
