#!/usr/bin/python3
import argparse
import collections
import enum
import jinja2
import json
import os
import pathlib
import random
import re
import shlex
import string
import subprocess
import sys
import tempfile
import time

TEMPLATE_FILE = pathlib.Path(__file__).parent / 'config.yml'

TEXTS = {
    'de': "Sie steht Ihnen bald wieder zur Verfügung.",
    'en': "Please try again later.",
    'fr': "Il sera à nouveau disponible bientôt.",
    'it': "Sarà di nuovo disponibile presto.",
}

TEXTS_TILL = {
    'de': "Sie steht Ihnen ab {} wieder zur Verfügung.",
    'en': "Please try again on {}.",
    'fr': "Il sera à nouveau disponible à partir du {}.",
    'it': "Sarà di nuovo disponibile da {}.",
}
assert TEXTS.keys() == TEXTS_TILL.keys()
LANGS = sorted(TEXTS.keys())

class Status(enum.Enum):
    STARTED = enum.auto()
    STOPPED = enum.auto()
    UNKNOWN = enum.auto()

BOLD_START = '\033[1m'
STYLE_RESET = '\033[0m'
CYAN_START = '\033[36m'
MAGENTA_START = '\033[35m'
COLOR_RESET = '\033[39m'

def style(start, end, text):
    if sys.stdout.isatty():
        return f'{start}{text}{end}'
    else:
        return text

def bold(text):
    return style(BOLD_START, STYLE_RESET, text)

def cyan(text):
    return style(CYAN_START, COLOR_RESET, text)

def magenta(text):
    return style(MAGENTA_START, COLOR_RESET, text)

def parse_args():
    def bypass_name(value):
        pattern = '^[A-Za-z0-9_-]+$'
        if not re.search(pattern, value):
            raise argparse.ArgumentTypeError(f'bypass name did not match expression {pattern}')
        return value

    def add_installation_arg(parser):
        parser.add_argument('installation', nargs='?',
                            help='Installation for which the maintenance page is'
                                 ' manipulated. By default, the installation selected'
                                 ' by `oc project <project>` is used.')

    prog = pathlib.Path(sys.argv[0]).stem
    def colored_cmd(*args):
        return magenta(' '.join(shlex.quote(arg) for arg in args))

    epilogue = f"""\
    Make sure you're logged in on OpenShift:

        $ {colored_cmd("oc", "login", "-w")}

    {bold("Examples")}

    Start maintenance page:

        $ {colored_cmd(prog, "start")}

    Stop Nice after starting maintenance page:

        $ {colored_cmd(prog, "--auto-start", "start")}

    Stop maintenance page:

        $ {colored_cmd(prog, "stop")}

    Start Nice before stopping maintenance page:

        $ {colored_cmd(prog, "--auto-scale", "stop")}

    Start Nice while maintenance page is running or stopped:

        $ {colored_cmd("oc", "scale", "--replicas=1", "deployment/nice")}

    Stop Nice while maintenance page is running or stopped:

        $ {colored_cmd("oc", "scale", "--replicas=0", "deployment/nice")}\
    """

    parser = argparse.ArgumentParser(
            description='Control maintenance page.',
            epilog=epilogue,
            formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument('--auto-scale', '-a', action='store_true',
                        help='Automatically stop Nice after maintenance page is enabled,'
                             ' and start Nice before maintenance page is disabled. When'
                             ' used with status, whether Nice is running is taken into'
                             ' account.')

    subparsers = parser.add_subparsers(title='command', dest='command')

    parser_start = subparsers.add_parser('start')
    add_installation_arg(parser_start)
    parser_start.add_argument('--till', '-t',
                              help='Until value printed on page when no language'
                                   '-specific value is specified.')

    parser_bypass = parser_start.add_mutually_exclusive_group()
    parser_bypass.add_argument('--bypass-name', default='bypass', type=bypass_name,
                               help='Makes maintenance page bypass available at'
                                    ' /_maintenance/{bypass_name}. Defaults to %(default)r.')
    parser_bypass.add_argument('--random-bypass-name', action='store_const', dest='bypass_name',
                               const=''.join(random.choice(string.ascii_letters) for _ in range(30)),
                               help='Randomly generate a name for the bypass page.')

    parser_start.add_argument('--status-tocco-code', default=200, choices=[200, 503], type=int,
                           help='HTTP status code returned for /status-tocco while'
                                ' maintenance page is enabled. Default is %(default)d.')

    for lang in LANGS:
        parser_start.add_argument(f'--till-{lang}',
                                  help='Language-specific until value.')
    parser_start.add_argument('--replicas', '-r', default=1, type=int)
    parser_start.add_argument('--self-test', action='store_true', help=argparse.SUPPRESS)

    parser_stop = subparsers.add_parser('stop')
    add_installation_arg(parser_stop)

    parser_status = subparsers.add_parser('status')
    add_installation_arg(parser_status)

    args = parser.parse_args()

    if args.command is None:
        parser.error('Command missing.')

    if args.command == 'start':
        for lang in LANGS:
            field_name = f'till_{lang}'
            value = getattr(args, field_name)
            if value is None:
                setattr(args, field_name, args.till)

    if args.command == 'start' and args.replicas < 1:
        parser.error('Number of replicas must be at least one.')

    return args


def oc_build_command(installation, args):
    cmd = [ 'oc' ]
    if installation is not None:
        cmd.extend(('-n', 'nice-' + installation))
    cmd.extend(args)
    return cmd


def oc_check_call(installation, args, **kwargs):
    command = oc_build_command(installation, args)
    return subprocess.check_call(command, **kwargs)


def oc_check_output(installation, args, **kwargs):
    kwargs.setdefault('universal_newlines', True)
    command = oc_build_command(installation, args)
    return subprocess.check_output(command, **kwargs)


def get_host_name_of_main_ingress(installation):
    text = oc_check_output(
        installation,
        ['get', '-o', 'json', 'ingress', 'nice']
    )
    return json.loads(text)['spec']['rules'][0]['host']


def get_ingresses(installation):
    text = oc_check_output(
        installation,
        ['get', '-o', 'json', '-l', 'app=nice', 'ingresses']
    )
    return json.loads(text)


def redirect_ingresses(installation, service_name, *, dry_run=False):
    changed = []
    config = get_ingresses(installation)

    for ingress in config['items']:
        service = ingress['spec']['rules'][0]['http']['paths'][0]['backend']['service']
        if service['name'] != service_name:
            service['name'] = service_name
            changed.append(True)
            if not dry_run:
                command = ['patch', 'ingress', ingress['metadata']['name'], '-p', json.dumps(ingress)]
                oc_check_call(installation, command)
        else:
            changed.append(False)

    return changed


def get_scale_to_command(name, no):
    return ['scale', name, '--replicas', str(no)]


def get_shell_quoted_scale_to_command(installation, name, no):
    oc_args = get_scale_to_command(name, no)
    return ' '.join(shlex.quote(arg) for arg in oc_build_command(installation, oc_args))


def scale_to(installation, name, no):
    oc_check_call(installation, get_scale_to_command(name, no))


def jinja_env():
    env = jinja2.Environment(
            undefined=jinja2.runtime.StrictUndefined,
            loader=jinja2.FileSystemLoader('/')
    )
    env.filters['to_json'] = json.dumps
    return env


# TODO Remove when migration from DeploymentConfig to Deployment has been completed.
def get_resource_type(installation):
    output = oc_check_output(
        installation,
        ['get', 'deployment', 'nice', '--template', 'x', '--ignore-not-found=true'],
    )
    return 'deployment' if output == 'x' else 'dc'


def create_objects(installation, args, *, dry_run=False):
    vars = {
      'bypass_name': args.bypass_name,
      'status_tocco_code': args.status_tocco_code,
      'texts': {},
      'replicas': args.replicas,
      'mode': 'start',
    }

    with tempfile.NamedTemporaryFile('wt') as tmp_file:
        env = jinja_env()
        template = env.get_template(TEMPLATE_FILE.as_posix())

        for lang in LANGS:
            till = getattr(args, f'till_{lang}')
            text = TEXTS[lang] if till is None else TEXTS_TILL[lang].format(till)
            vars['texts'][lang] = text

        tmp_file.write(template.render(vars))
        tmp_file.flush()

        if not dry_run:
            oc_check_call(installation, ['apply', '-f', tmp_file.name])


def delete_objects(installation):
    env = jinja_env()
    definition = env.get_template(TEMPLATE_FILE.as_posix()).render(mode='stop')
    try:
        oc_check_output(
                installation,
                ['delete', '--ignore-not-found=true', '-f', '-'],
                input=definition,
        )
    except subprocess.CalledProcessError as e:
        print("ERROR: failed to remove configuration, proceeding …")


def get_status(installation, resource_type, *, auto_scale):
    ingress_changes = redirect_ingresses(installation, 'nice', dry_run=True)
    pods = get_pods(installation, 'app=nginx-maintenance')

    replicas = None
    if auto_scale:
        replicas = oc_check_output(
            installation,
            ['get', resource_type, 'nice', '--template', '{{ .spec.replicas }}'],
        )
        replicas = int(replicas)

    if all(ingress_changes) and len(pods) > 0 and (not auto_scale or replicas == 0):
        return Status.STARTED
    elif not any(ingress_changes) and len(pods) == 0 and (not auto_scale or replicas >= 1):
        return Status.STOPPED
    else:
        return Status.UNKNOWN


def get_pods(installation, label, *, ready_only=False):
    command = ['get', 'pods', '-l', label, '-o', 'json']
    pods = json.loads(oc_check_output(installation, command))['items']
    if ready_only:
        pods = [ pod for pod in pods if all_containers_running(pod) ]
    return pods


def all_containers_running(pod):
    statuses = pod['status'].get('containerStatuses')
    if statuses is None:
        # containerStatuses is sometimes unavailable during very
        # early pod creation.
        return False
    for container in statuses:
        if not container['ready']:
            return False
    return True


def print_status_and_exit(installation, resource_type, auto_scale):
    status = get_status(installation, resource_type, auto_scale=auto_scale)
    if status == Status.STARTED:
        print('running')
        exit(0)
    elif status == Status.STOPPED:
        print('stopped')
        exit(1)
    else:
        assert status == Status.UNKNOWN
        print('unknown (partially stopped or started)')
        exit(2)


def wait_until_ready(installation, label, retry_attempts=60):
    print(f"wait until {label} container is ready")
    for i in range(retry_attempts):
        try:
            pods = get_pods(installation, label, ready_only=True)
            if len(pods) > 0:
                print(f"{label} is now ready")
                return True
        except subprocess.CalledProcessError as e:
            print('ERROR:', e)

        time.sleep(1)

    raise TimeoutError("Giving up waiting until maintenance container is ready after {} seconds".format(retry_attempts))


def main():
    args = parse_args()

    resource_type = 'deployment' if args.command == "start" and args.self_test else get_resource_type(args.installation)
    resource_name = resource_type + '/nice'
    if args.command == 'start' and args.self_test:
        create_objects(args.installation, args, dry_run=True)
    elif args.command == 'start':
        host_name = get_host_name_of_main_ingress(args.installation)
        print(f'Starting maintenance page for {cyan(bold(host_name))}:')
        print()
        print('---')
        print()
        url = f'https://{host_name}/_maintenance/{args.bypass_name}'
        print(f'Bypass URL: {magenta(url)}')
        print()
        print('Use the above URL to access Nice while the maintenence page')
        print('is online.')
        print()
        print('---')
        print()
        print('You can freely start and stop the installation while the')
        print('maintenance page is active.')
        print()
        print('Start Nice:')
        print()
        start_command = get_shell_quoted_scale_to_command(args.installation, resource_name, 1)
        print(f'    $ {magenta(start_command)}')
        print()
        print('Stop Nice:')
        print()
        stop_command = get_shell_quoted_scale_to_command(args.installation, resource_name, 0)
        print(f'    $ {magenta(stop_command)}')
        print()
        print('---')
        print()

        if get_status(args.installation, resource_type, auto_scale=args.auto_scale) == Status.STARTED:
            print("maintenance mode is already enabled")
            return
        # update to allow changing text
        create_objects(args.installation, args)
        scale_to(args.installation, "deployment/maintenance", args.replicas)
        try:
            wait_until_ready(args.installation, 'app=nginx-maintenance')
        except TimeoutError:
            delete_objects(args.installation)
        redirect_ingresses(args.installation, 'nginx-maintenance')
        if args.auto_scale:
            scale_to(args.installation, resource_name, 0)
    elif args.command == 'stop':
        host_name = get_host_name_of_main_ingress(args.installation)
        print(f'Stopping maintenance page for {cyan(bold(host_name))}:')
        print()
        if get_status(args.installation, resource_type, auto_scale=args.auto_scale) == Status.STOPPED:
            print("maintenance mode is already disabled")
            return
        if args.auto_scale:
            scale_to(args.installation, resource_name, 1)
            wait_until_ready(args.installation, 'run=nice', retry_attempts=180)
        redirect_ingresses(args.installation, 'nice')
        delete_objects(args.installation)
    elif args.command == 'status':
        host_name = get_host_name_of_main_ingress(args.installation)
        print(f'Status for {cyan(bold(host_name))}:')
        print()
        print_status_and_exit(args.installation, resource_type, auto_scale=args.auto_scale)
    else:
        raise AssertionError('Unknown command {!r}'.format(args.command))


if __name__ == '__main__':
    main()
