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

import os
import sys
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


CLEANUP_FSP_SCRIPT = os.path.join(os.path.dirname(__file__),
                                  "cleanup-old-jit-fsps.sh")

logger = logging.getLogger(__name__)


def do_patching(ctx):

    # Make sure the script can be executed
    (rc, stdout, stderr) = run_command(['chmod', '+x', CLEANUP_FSP_SCRIPT])

    if rc != 0:
        _raise_error('Failed to make Foreign Security Principal cleanup '
                     'script executable: %s' % CLEANUP_FSP_SCRIPT,
                     stdout, stderr)

    # Run the cleanup script, which looks for a GovCloud scenario in which
    # an Oauth2 external identity provider is configured. If detected, this
    # script removes all ForeignSecurityPrincipals that were JITed for that
    # provider during login
    (rc, stdout, stderr) = run_command(CLEANUP_FSP_SCRIPT)

    if rc != 0:
        _raise_error('Failed to run Foreign Security Principal cleanup '
                     'script %s (rc %d)' % (CLEANUP_FSP_SCRIPT, rc),
                     stdout, stderr)

    logger.info(stdout)
    logger.info('"JIT FSP cleanup" command executed successfully')


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