#! /usr/bin/env python3
import argparse
import configparser
from manage_users import NoSuchUserError
from manage_users.script_helpers import playbook_load_or_prompt_for_create
import os
import sys


def main(args, config_path):
    """
        Modify a user in the configuration management system.

        Keyword arguments:
        args -- A list of arguments from the command line with the program
                name removed (sys.argv[1:]).
        config_path -- The path to the manage_users config file.
    """
    parser = argparse.ArgumentParser(
        description='Modify an existing user in the configuration management'
                    ' system.',
        prog='manuse modify',
    )

    parser.add_argument(
        '-u', '--username',
        help="The username of the user you wish to modify.",
        required=True,
    )

    enable_choice = parser.add_mutually_exclusive_group()
    enable_choice.add_argument(
        '-e', '--enable',
        help='Enable this user, allowing them their configured access.',
        action='store_true',
        default=False,
    )
    enable_choice.add_argument(
        '-d', '--disable',
        help='Disable this user, denying them any access.',
        action='store_true',
        default=False,
    )

    args = parser.parse_args(args)

    config = configparser.ConfigParser()
    try:
        with open(config_path) as config_handle:
            config.readfp(config_handle)
    except FileNotFoundError:
        sys.stderr.write(
            ('Could not find config file in {config_path}\n'
             'Please run configuration utility before use:\n').format(
                config_path=config_path
            )
        )
        sys.exit(1)

    # Find out where the playbook is
    playbook_path = config.get('ansible', 'playbook_path')

    if playbook_path is None:
        sys.stderr.write(
            ('Could not find playbook path in configuration.\n'
             'Please run configuration utility to set playbook path.\n')
        )
        sys.exit(1)

    # Get the base ID or use a default
    base_id = int(config.get('general', 'base_id')) or 10000

    user_manager = playbook_load_or_prompt_for_create(
        playbook_path=playbook_path,
        base_id=base_id,
    )

    if args.enable:
        action = user_manager.enable_user
    elif args.disable:
        action = user_manager.disable_user
    else:
        action = None

    if action is not None:
        try:
            action(
                user=args.username,
            )
            user_manager.save_playbook()
        except NoSuchUserError:
            sys.stderr.write(
                'User {user} does not exist, doing nothing.\n'.format(
                    user=args.username,
                )
            )
            sys.exit(1)

    if args.disable:
        # Helpful warning if a user has been disabled to avoid security
        # incidents inspired by forgetfulness
        print('Be aware that changes will not affect servers until the next'
              ' run of your configuration management tool.')

if __name__ == '__main__':
    config_path = os.path.join(
        os.path.expanduser('~'),
        '.manage_users.conf'
    )
    main(sys.argv[1:], config_path)
