#!/usr/bin/python3

# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2019 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 logging
import sys
import signal
import os
from lib389.utils import get_instance_list
from lib389 import DirSrv
from lib389.cli_ctl import instance as cli_instance
from lib389.cli_ctl import dbtasks as cli_dbtasks
from lib389.cli_ctl import tls as cli_tls
from lib389.cli_ctl import health as cli_health
from lib389.cli_ctl import nsstate as cli_nsstate
from lib389.cli_ctl.instance import instance_remove_all
from lib389.cli_base import (
    _get_arg,
    disconnect_instance,
    setup_script_logger,
    format_error_to_dict)
from lib389._constants import DSRC_CONTAINER

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose',
        help="Display verbose operation tracing during command execution",
        action='store_true', default=False
    )
parser.add_argument('instance', nargs='?', default=False,
        help="The name of the instance to act upon",
    )
parser.add_argument('-j', '--json',
        help="Return result in JSON object",
        default=False, action='store_true'
    )
parser.add_argument('-l', '--list',
        help="List available Directory Server instances",
        default=False, action='store_true'
    )

parser.add_argument('--remove-all', nargs="?", default=False, const=None,
        help="Remove all instances of Directory Server (you can also provide an optional directory prefix for this argument)",
    )

subparsers = parser.add_subparsers(help="action")
# We can only use the instance tools like start/stop etc in a non-container
# environment. If we are in a container, we only allow the tasks.
if not os.path.exists(DSRC_CONTAINER):
    cli_instance.create_parser(subparsers)
cli_dbtasks.create_parser(subparsers)
cli_tls.create_parser(subparsers)
cli_health.create_parser(subparsers)
cli_nsstate.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__':
    args = parser.parse_args()

    log = setup_script_logger('dsctl', args.verbose)

    log.debug("The 389 Directory Server Administration 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")

    log.debug("Called with: %s", args)

    if args.list:
        insts = get_instance_list()
        for inst in insts:
            print(inst)
        sys.exit(0)
    elif args.remove_all is not False:
        instance_remove_all(log, args)
        sys.exit(0)
    elif not args.instance:
        log.error("error: the following arguments are required: instance")
        parser.print_help()
        sys.exit(1)

    # 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)

    # Connect
    inst = DirSrv(verbose=args.verbose)

    result = True

    # Allocate the instance based on name
    insts = []
    if args.verbose:
        insts = inst.list(serverid=args.instance)
    else:
        signal.signal(signal.SIGINT, signal_handler)
        try:
            insts = inst.list(serverid=args.instance)
        except (PermissionError, IOError) as e:
            log.error("Unable to access instance information. Are you running as the correct user? (usually dirsrv or root)")
            msg = format_error_to_dict(e)
            log.error("Error: %s" % " - ".join(msg.values()))
            sys.exit(1)
        except Exception as e:
            msg = format_error_to_dict(e)
            log.error("Error: %s" % " - ".join(msg.values()))
            sys.exit(1)
    if len(insts) != 1:
        log.error("No such instance '%s'" % args.instance)
        log.error("Unable to access instance information. Are you running as the correct user? (usually dirsrv or root)")
        sys.exit(1)

    inst.allocate(insts[0])
    log.debug('Instance allocated')

    try:
        result = args.func(inst, log, args)
    except Exception as e:
        log.debug(e, exc_info=True)
        msg = format_error_to_dict(e)
        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)
