#!/usr/bin/python3

# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2020 Red Hat, Inc.
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---
#
# PYTHON_ARGCOMPLETE_OK

import argparse, argcomplete
import ldap
import sys
import signal
import json
from lib389._constants import DSRC_HOME
from lib389.cli_conf import config as cli_config
from lib389.cli_conf import backend as cli_backend
from lib389.cli_conf import directory_manager as cli_directory_manager
from lib389.cli_conf import plugin as cli_plugin
from lib389.cli_conf import schema as cli_schema
from lib389.cli_conf import monitor as cli_monitor
from lib389.cli_conf import saslmappings as cli_sasl
from lib389.cli_conf import pwpolicy as cli_pwpolicy
from lib389.cli_conf import backup as cli_backup
from lib389.cli_conf import replication as cli_replication
from lib389.cli_conf import chaining as cli_chaining
from lib389.cli_conf import conflicts as cli_repl_conflicts
from lib389.cli_conf import security as cli_security
from lib389.cli_base import disconnect_instance, connect_instance
from lib389.cli_base.dsrc import dsrc_to_ldap, dsrc_arg_concat
from lib389.cli_base import setup_script_logger
from lib389.cli_base import format_error_to_dict


parser = argparse.ArgumentParser(allow_abbrev=True)
parser.add_argument('instance',
        help="The instance name OR the LDAP url to connect to, IE localhost, ldap://mai.example.com:389",
    )
parser.add_argument('-v', '--verbose',
        help="Display verbose operation tracing during command execution",
        action='store_true', default=False
    )
parser.add_argument('-D', '--binddn',
        help="The account to bind as for executing operations",
        default=None
    )
parser.add_argument('-w', '--bindpw',
        help="Password for binddn",
        default=None
    )
parser.add_argument('-W', '--prompt',
        action='store_true', default=False,
        help="Prompt for password for the bind DN"
    )
parser.add_argument('-y', '--pwdfile',
        help="Specifies a file containing the password for the binddn",
        default=None
    )
parser.add_argument('-b', '--basedn',
        help="Basedn (root naming context) of the instance to manage",
        default=None
    )
parser.add_argument('-Z', '--starttls',
        help="Connect with StartTLS",
        default=False, action='store_true'
    )
parser.add_argument('-j', '--json',
        help="Return result in JSON object",
        default=False, action='store_true'
    )

subparsers = parser.add_subparsers(help="resources to act upon")

cli_backend.create_parser(subparsers)
cli_backup.create_parser(subparsers)
cli_chaining.create_parser(subparsers)
cli_config.create_parser(subparsers)
cli_directory_manager.create_parsers(subparsers)
cli_monitor.create_parser(subparsers)
cli_plugin.create_parser(subparsers)
cli_pwpolicy.create_parser(subparsers)
cli_replication.create_parser(subparsers)
cli_sasl.create_parser(subparsers)
cli_security.create_parser(subparsers)
cli_schema.create_parser(subparsers)
cli_repl_conflicts.create_parser(subparsers)

argcomplete.autocomplete(parser)

# handle a control-c gracefully
def signal_handler(signal, frame):
    print('\n\nExiting...')
    sys.exit(0)


if __name__ == '__main__':

    defbase = ldap.get_option(ldap.OPT_DEFBASE)
    args = parser.parse_args()
    log = setup_script_logger('dsconf', args.verbose)

    log.debug("The 389 Directory Server Configuration Tool")
    # Leave this comment here: UofA let me take this code with me provided
    # I gave attribution. -- wibrown
    log.debug("Inspired by works of: ITS, The University of Adelaide")

    # Now that we have our args, see how they relate with our instance.
    dsrc_inst = dsrc_to_ldap(DSRC_HOME, args.instance, log.getChild('dsrc'))

    # Now combine this with our arguments
    dsrc_inst = dsrc_arg_concat(args, dsrc_inst)

    log.debug("Called with: %s" % args)
    log.debug("Instance details: %s" % dsrc_inst)

    # Assert we have a resources to work on.
    if not hasattr(args, 'func'):
        log.error("No action provided, here is some --help.")
        parser.print_help()
        sys.exit(1)

    if not args.verbose:
        signal.signal(signal.SIGINT, signal_handler)

    # Connect
    # We don't need a basedn, because the config objects derive it properly
    inst = None
    result = False
    try:
        inst = connect_instance(dsrc_inst=dsrc_inst, verbose=args.verbose, args=args)
        result = args.func(inst, None, log, args)
        if args.verbose:
            log.info("Command successful.")
    except Exception as e:
        log.debug(e, exc_info=True)
        msg = format_error_to_dict(e)

        if args and args.json:
            sys.stderr.write(f"{json.dumps(msg, indent=4)}\n")
        else:
            log.error("Error: %s" % " - ".join(str(val) for val in msg.values()))
        result = False

    disconnect_instance(inst)

    # Done!
    if result is False:
        sys.exit(1)
