# Copyright 2016-2021 VMware, Inc. All rights reserved. -- VMware Confidential
"""
license component module following the B2B patching principles.
"""

import os
import sys
import vcsa_utils
import logging
import shutil
from distutils.dir_util import copy_tree

from .utils import COMPONENT_NAME, run_firstboot

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
from fss_utils import getTargetFSS
from extensions import extend, Hook
from l10n import msgMetadata as _T, localizedString as _
from vcsa_utils import getComponentDiscoveryResult
from reporting import getProgressReporter


LICENSE_SPEC_PROPERTIES = "/etc/vmware-cis-license/licensespec.properties"
LOG_4J_PROPERTIES = "/etc/vmware-cis-license/log4j.properties"
PH_PROPERTIES = "/etc/vmware-cis-license/ph.properties"
SUBSCRIPTION_MANAGEMENT_PROPERTIES = "/etc/vmware-cis-license/subscription.management.properties"
LS_PROPERTIES = "/etc/vmware-cis-license/ls.properties"
LICENSE_PROPERTIES = "/etc/vmware-cis-license/license.properties"
SUBSCRIPTION_LOG_DIRECTORY = "/var/log/vmware/cis-license/slms/"
SUBSCRIPTION_CONFIG_DIRECTORY_OLD = "/etc/vmware-cis-license/slms/"
SUBSCRIPTION_CONFIG_DIRECTORY = "/var/lib/vmware/cis-license/slms/"
LICENSE_ENDPOINTS_PROXY_CONF = "/etc/vmware-rhttpproxy/endpoints.conf.d/license-proxy.conf"
RDU_FLAG_FILE = "/etc/vmware-cis-license/rdu_marker.txt"

logger = logging.getLogger(__name__)


@extend(Hook.Discovery)
def discover(ctx):
    """DiscoveryResult discover(PatchContext ctx) throw UserError"""
    # Override the default replication config so to not preserve a file containing volatile state during upgrade
    logger.info('Executing Discovery Hook for License Service')

    # this is needed, as the replicationConfig overrides what is in the BR config, if
    # the source OR the destination file paths match.
    source_subscription_config_dir = ''
    if os.path.exists(SUBSCRIPTION_CONFIG_DIRECTORY_OLD):
        source_subscription_config_dir = SUBSCRIPTION_CONFIG_DIRECTORY_OLD
    else:
        source_subscription_config_dir = SUBSCRIPTION_CONFIG_DIRECTORY

    replicationConfig = {
       LICENSE_SPEC_PROPERTIES: LICENSE_SPEC_PROPERTIES,
       SUBSCRIPTION_LOG_DIRECTORY: SUBSCRIPTION_LOG_DIRECTORY,
       source_subscription_config_dir: SUBSCRIPTION_CONFIG_DIRECTORY,
       RDU_FLAG_FILE: RDU_FLAG_FILE,

       LICENSE_PROPERTIES: None,
       LS_PROPERTIES: None,
       LOG_4J_PROPERTIES: None,
       PH_PROPERTIES: None,
       SUBSCRIPTION_MANAGEMENT_PROPERTIES: None,
       LICENSE_ENDPOINTS_PROXY_CONF: None
    }

    logger.info('Replication Config for Discovery Hook for License Service %s', str(replicationConfig))
    return getComponentDiscoveryResult(COMPONENT_NAME, replicationConfig=replicationConfig)


@extend(Hook.Patch)
def patch(ctx):
   # This hook is invoked after the rpms are installed.
   logger.info('Executing Patch Hook for License Service')

   progress_reporter = getProgressReporter()
   progress_reporter.updateProgress(0, _(_T('license.patch.begin',
                                            'Start License patching')))

   if os.path.exists(SUBSCRIPTION_CONFIG_DIRECTORY_OLD):
      copy_tree(SUBSCRIPTION_CONFIG_DIRECTORY_OLD, SUBSCRIPTION_CONFIG_DIRECTORY)
      shutil.rmtree(SUBSCRIPTION_CONFIG_DIRECTORY_OLD)

   ## We do not need to do anything for patching now, when we do, we should run firstboot.
   ## Uncomment below line in that case.
   # run_firstboot(ctx)

   progress_reporter.updateProgress(100, _(_T('license.patch.complete',
                                              'Patching License completed')))


@extend(Hook.Requirements)
def collectRequirements(ctx):
    """RequirementsResult collectRequirements(PatchContext ctx)"""
    pass


@extend(Hook.Validation)
def validate(ctx):
    """ValidationResult validate(PatchContext ctx)"""
    pass


@extend(Hook.Expand)
def expand(context):
    """void prepare(PatchContext ctx) throw UserError"""
    progress_reporter = getProgressReporter()
    progress_reporter.updateProgress(0, _(_T('license.patch.begin', 'Start License expand hook')))

    logger.info('Executing Expand Hook for Licensing Service')
    if not os.path.exists(RDU_FLAG_FILE):
        open(RDU_FLAG_FILE, 'a').close()

    progress_reporter.updateProgress(100, _(_T('license.patch.complete', 'License exphand hook completed')))


#We run the firstboot here using pre start script


@extend(Hook.Contract)
def contract(ctx):
    """void patch(PatchContext ctx) throw UserError"""
    progress_reporter = getProgressReporter()
    progress_reporter.updateProgress(0, _(_T('license.contract.begin', 'Start License Contract hook')))

    if os.path.exists(RDU_FLAG_FILE):
        os.remove(RDU_FLAG_FILE)

    progress_reporter.updateProgress(100, _(_T('license.contract.complete', 'License Contract hook completed')))

@extend(Hook.Revert)
def revert(ctx):
    """void revert(PatchContext ctx) throw UserError"""
    progress_reporter = getProgressReporter()
    progress_reporter.updateProgress(0, _(_T('license.revert.begin', 'Start License Revert hook')))

    if os.path.exists(RDU_FLAG_FILE):
        os.remove(RDU_FLAG_FILE)

    progress_reporter.updateProgress(100, _(_T('license.revert.complete', 'License Revert hook completed')))