#!/usr/bin/python3

# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2016, William Brown <william at blackhats.net.au>
# Copyright (C) 2024 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 json
import sys
import signal
import ldap
import argparse
import argcomplete
from lib389.utils import get_instance_list, instance_choices
from lib389._constants import DSRC_HOME
from lib389.cli_idm import _get_basedn_arg
from lib389.cli_idm import account as cli_account
from lib389.cli_idm import initialise as cli_init
from lib389.cli_idm import organizationalunit as cli_ou
from lib389.cli_idm import group as cli_group
from lib389.cli_idm import posixgroup as cli_posixgroup
from lib389.cli_idm import uniquegroup as cli_uniquegroup
from lib389.cli_idm import user as cli_user
from lib389.cli_idm import client_config as cli_client_config
from lib389.cli_idm import role as cli_role
from lib389.cli_idm import service as cli_service
from lib389.cli_base import connect_instance, disconnect_instance, setup_script_logger
from lib389.cli_base.dsrc import dsrc_to_ldap, dsrc_arg_concat
from lib389.cli_base import format_error_to_dict
from lib389.cli_base import parent_argparser

parser = argparse.ArgumentParser(allow_abbrev=True, parents=[parent_argparser])
# First, add the LDAP options
parser.add_argument('instance',
        help="The name of the instance or its LDAP URL, such as ldap://server.example.com:389",
    ).completer = instance_choices
parser.add_argument('-b', '--basedn',
        help="Base DN (root naming context) of the instance to manage",
        default=None
    )
parser.add_argument('-D', '--binddn',
        help="The account to bind as for executing operations",
        default=None
    )
parser.add_argument('-w', '--bindpw',
        help="Password for the bind DN",
        default=None
    )
parser.add_argument('-W', '--prompt',
        action='store_true', default=False,
        help="Prompt for password of the bind DN"
    )
parser.add_argument('-y', '--pwdfile',
        help="Specifies a file containing the password of the bind DN",
        default=None
    )
parser.add_argument('-Z', '--starttls',
        help="Connect with StartTLS",
        default=False, action='store_true'
    )
subparsers = parser.add_subparsers(help="resources to act upon")
# Call all the other cli modules to register their bits
cli_account.create_parser(subparsers)
cli_group.create_parser(subparsers)
cli_init.create_parser(subparsers)
cli_ou.create_parser(subparsers)
cli_posixgroup.create_parser(subparsers)
cli_user.create_parser(subparsers)
cli_client_config.create_parser(subparsers)
cli_role.create_parser(subparsers)
cli_service.create_parser(subparsers)
cli_uniquegroup.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('dsidm', args.verbose)

    log.debug("The 389 Directory Server Identity Manager")
    # 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'):
        errmsg = "No action provided, here is some --help."
        if args.json:
            sys.stderr.write('{"desc": "%s"}\n' % errmsg)
        else:
            log.error(errmsg)
            parser.print_help()
        sys.exit(1)

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

    ldapurl = args.instance

    # Connect
    inst = None
    result = False
    try:
        inst = connect_instance(dsrc_inst=dsrc_inst, verbose=args.verbose, args=args)
        basedn = _get_basedn_arg(inst, args, log, msg="Enter basedn")
        if basedn is None:
            errmsg = "Must provide a basedn!"
            if args.json:
                sys.stderr.write('{"desc": "%s"}\n' % errmsg)
            else:
                log.error(errmsg)
            sys.exit(1)
        result = args.func(inst, basedn, 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.json:
            sys.stderr.write(f"{json.dumps(msg, indent=4)}\n")
        else:
            if 'desc' in msg:
                log.error(f"Error: {msg['desc']}")
            else:
                log.error("Error: %s" % " - ".join(str(val) for val in msg.values()))
        result = False

    disconnect_instance(inst)

    if result is False:
        sys.exit(1)
