# Copyright 2020 VMware, Inc.
# All rights reserved. -- VMware Confidential

import os
import sys
import re
import logging

vmware_python_path = os.getenv('VMWARE_PYTHON_PATH')
if vmware_python_path and os.path.exists(vmware_python_path):
    sys.path.append(vmware_python_path)

from cis.utils import run_command


VMIDENTITY_RHTTP_CONF_FILE =\
    '/etc/vmware-rhttpproxy/endpoints.conf.d/vmidentity.conf'
SYSTEM_SDK_REGEX = r'^/sso-adminserver/system-sdk\s'
SYSTEM_SDK_ROUTE =\
    '/sso-adminserver/system-sdk remote localhost:7080/sso-adminserver/sdk/%s allow reject\n'

SYSTEM_STSSERVICE_REGEX = r'^/sts/system-STSService\s'
SYSTEM_STSSERVICE_ROUTE =\
    '/sts/system-STSService remote localhost:7080/sts/STSService/%s allow reject\n'

logger = logging.getLogger(__name__)


def do_patching(ctx):

    # Only attempt the patching if the vmidentity.conf rhttpproxy file exists
    if not os.path.isfile(VMIDENTITY_RHTTP_CONF_FILE):
        logger.info('Config file for vmidentity rhttpproxy routing '
                    'does not exist: %s. Skipping patching ...' %
                    VMIDENTITY_RHTTP_CONF_FILE)
        return

    # Get the current system domain name
    (rc, stdout, stderr) = run_command(['/usr/lib/vmware-vmafd/bin/vmafd-cli',
                                        'get-domain-name',
                                        '--server-name',
                                        'localhost'])
    if rc != 0:
        _raise_error('Failed to retrieve system domain name via VMAFD',
                     stdout, stderr)
    system_domain = stdout.strip()

    # Get the current rhttpproxy config file contents
    with open(VMIDENTITY_RHTTP_CONF_FILE, 'r') as file:
        conf_lines = file.readlines()

    # Add the sso-adminserver/system-sdk route to the config, overwriting any
    # existing route for this pattern that may be present
    system_sdk_route = SYSTEM_SDK_ROUTE % system_domain
    system_stsservice_route = SYSTEM_STSSERVICE_ROUTE % system_domain
    updated_config = [r for r in conf_lines
                      if not re.search(SYSTEM_SDK_REGEX, r) and
                         not re.search(SYSTEM_STSSERVICE_REGEX, r)]
    updated_config.append(system_sdk_route)
    updated_config.append(system_stsservice_route)
    logger.info('Writing updated rhttpproxy config for vmidentity:\n%s' %
                updated_config)

    # Write the full updated config back to the same file
    with open(VMIDENTITY_RHTTP_CONF_FILE, 'w') as file:
        file.writelines(updated_config)

    # Trigger rhttpproxy to reload its configuration and pick up the new route,
    # if it is running
    (rc, stdout, _) = run_command(['pidof', 'rhttpproxy'])
    if rc == 0 and stdout:
        rhttpproxy_pid = stdout.strip()
        (rc, stdout, stderr) = run_command(['kill', '-1', rhttpproxy_pid])
        if rc != 0:
            _raise_error('Failed to kill rhttpproxy process with pid %s '
                         'to pick up new vmidentity system-sdk routing' %
                         rhttpproxy_pid, stdout, stderr)


def _raise_error(msg, stdout=None, stderr=None):
    logger.error(msg)
    if stdout:
        logger.error(stdout)
    if stderr:
        logger.error(stderr)
    raise RuntimeError(msg)
