#!/usr/bin/env python
# Copyright 2017-2021 VMware, Inc. All rights reserved. -- VMware Confidential
"""
Analytics component module following the B2B patching principles.
"""

import os
import logging
import shutil
import sys

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

logger = logging.getLogger(__name__)

MARKER_FILE = "/etc/vmware-analytics/rdu_marker.txt"
SILENCED_HEALTH_CHECKS_DIRECTORY_OLD = "/etc/vmware-analytics/silenced-health-tests/"
SILENCED_HEALTH_CHECKS_LOCATION_OLD = "/etc/vmware-analytics/silenced-health-tests/silent.json"
SILENCED_HEALTH_CHECKS_LOCATION = "/var/lib/vmware/analytics/silenced-health-tests/silent.json"

@extend(Hook.Discovery)
def discover(ctx):
   logger.info('Executing Discovery Hook for Analytics Service')

   # By default RDU will transfer all the files under backuprestore/analytics.json to the new deployment
   # and overwrite the same files there. With replicationConfig we can override this behaviour by
   # explicitely mapping files from the source that we want to transfer or to the target or map them to 
   # None if we want them to be ignored.

   # On builds before CL 9211866 the silent.json file is in a different location.
   # We have to account for that in cases when the RDU source build is older.
   source_silenced_health_checks_location = ""
   if os.path.exists(SILENCED_HEALTH_CHECKS_LOCATION_OLD):
      source_silenced_health_checks_location = SILENCED_HEALTH_CHECKS_LOCATION_OLD
   else:
      source_silenced_health_checks_location = SILENCED_HEALTH_CHECKS_LOCATION

   replicationConfig = {"/etc/vmware-analytics/log4j.properties": None,
                        "/etc/vmware-analytics/ph-configuration.properties": None,
                        "/etc/vmware-analytics/phservice.properties": None,
                        "/etc/vmware-analytics/phservice-install.properties": None,
                        "/etc/vmware-rhttpproxy/endpoints.conf.d/analytics-proxy.conf": None,
                        "/var/lib/vmware/analytics/ph-persistence.properties": None,
                        source_silenced_health_checks_location: SILENCED_HEALTH_CHECKS_LOCATION,
                        "/storage/log/vmware/analytics/stage/": "/storage/log/vmware/analytics/stage/",
                        "/storage/log/vmware/analytics/prod/": "/storage/log/vmware/analytics/prod/",
                        MARKER_FILE: MARKER_FILE}


   return getComponentDiscoveryResult(COMPONENT_NAME, replicationConfig=replicationConfig)

@extend(Hook.Expand)
def expand(ctx):
   '''void expand(PatchContext ctx) throw UserError'''

   progress_reporter = getProgressReporter()
   progress_reporter.updateProgress(0, _(_T('analytics.expand.begin',
                                            'Start Analytics expand')))

   if getTargetFSS("NDU_Limited_Downtime"):
      logger.info('Executing Expand Hook for Analytics Service')
      if not os.path.exists(MARKER_FILE):
         open(MARKER_FILE, 'w').close()

   progress_reporter.updateProgress(100, _(_T('analytics.expand.complete',
                                              'Expand Analytics completed')))

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

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

   # In case of B2B from an older build we need to delete the ph-persistence file from its old location
   if os.path.exists('/etc/vmware-analytics/ph-persistence.properties'):
      os.remove('/etc/vmware-analytics/ph-persistence.properties')

   # Similarly for the silent.json file but we want to preserve its state after B2B
   if os.path.exists(SILENCED_HEALTH_CHECKS_LOCATION_OLD):
      shutil.copyfile(SILENCED_HEALTH_CHECKS_LOCATION_OLD, SILENCED_HEALTH_CHECKS_LOCATION)
      os.remove(SILENCED_HEALTH_CHECKS_LOCATION_OLD)

   # Remove the old silenced-health-tests directory even if it was empty
   if os.path.exists(SILENCED_HEALTH_CHECKS_DIRECTORY_OLD):
      os.rmdir(SILENCED_HEALTH_CHECKS_DIRECTORY_OLD)

   run_firstboot(ctx)

   progress_reporter.updateProgress(100, _(_T('analytics.patch.complete',
                                              'Patching Analytics completed')))

@extend(Hook.Contract)
def contract(ctx):
   '''void contract(PatchContext sharedCtx) throw UserError'''
   progressReporter = getProgressReporter()
   progressReporter.updateProgress(0, _(_T('analytics.contract.begin',
                                           'Start Analytics Service contract')))

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

   progressReporter.updateProgress(100, _(_T('analytics.contract.complete',
                                             'Contract Analytics Service completed')))

@extend(Hook.Revert)
def revert(ctx):
   '''void revert(PatchContext ctx) throw UserError'''
   progressReporter = getProgressReporter()
   progressReporter.updateProgress(0, _(_T('analytics.revert.begin',
                                           'Start Analytics Service revert')))

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

   progressReporter.updateProgress(100, _(_T('analytics.revert.complete',
                                             'Revert Analytics Service completed')))