#!/usr/bin/python3

# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2016, William Brown <william at blackhats.net.au>
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---
#
# PYTHON_ARGCOMPLETE_OK

import ldap
import argparse
import argcomplete
import sys
import signal
from lib389._constants import DSRC_HOME
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 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_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


parser = argparse.ArgumentParser(allow_abbrev=True)
# First, add the LDAP options
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('-b', '--basedn',
        help="Basedn (root naming context) of the instance to manage",
        default=None
    )
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 binddn"
    )
parser.add_argument('-y', '--pwdfile',
        help="Specifies a file containing the password for the bind DN",
        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")
# 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)

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'):
        log.error("No action provided, here is some --help.")
        parser.print_help()
        sys.exit(1)

    if dsrc_inst['basedn'] is None:
        log.error("Must provide a basedn!")
        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)
        result = args.func(inst, dsrc_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:
            log.error("Error: %s" % " - ".join(str(val) for val in msg.values()))
        result = False

    disconnect_instance(inst)

    if result is False:
        sys.exit(1)
