"""
Copyright 2020-2021 VMware, Inc.  All rights reserved. -- VMware Confidential
"""

import logging
import sys
import shutil

from vstats import utils
from cis.vecs import SsoGroup, vmafd_machine_id
from pathlib import Path


sys.path.append('/usr/lib/vmware-vmafd/lib64')
import vmafdpy3

logger = logging.getLogger(__name__)
PATCH_VERSION=5

VSTATS_GROUP = 'vStatsGroup'

SOLUTION_USER_NAME = 'vpxd-extension'

# config.json will be backed up as config.json.rpmsave after rpm install.
vstats_config_file_path = "/usr/lib/vmware-vstats/config/config.json"
vstats_config_file_new_path = "/var/lib/vmware-vstats/config/config.json"
suffix = ".rpmsave"

class SsoPatch:
    def __init__(self):
        vmafdClient = vmafdpy3.client('localhost')
        username = vmafdClient.GetMachineName()
        password = vmafdClient.GetMachinePassword()
        self.sso_group = SsoGroup(username, password)

    def add_user_to_group(self, group, user):
        """
        add user to the sso group
        :param group: sso group to which user is to be added
        :param user: user to be added to the sso group
        """
        logger.debug('Attempting to add user "%s" to group "%s"', user, group)
        if self.sso_group.add_user(group, user):
            logger.info('Added "%s" to "%s" group', user, group)
        else:
            logger.error('User "%s" could not be added to group "%s"',user, group)

def patch_sso_add_user_to_group() :
    # Add solution user to vstatsGroup to enable client profile creation profile
    # for host stats collection with a jwt token from host.
    sso_patch = SsoPatch()
    svc_username = SOLUTION_USER_NAME + "-" + vmafd_machine_id()
    sso_patch.add_user_to_group(VSTATS_GROUP, svc_username)

def doPatching(ctx):
    logger.info("Applying patch_04 on vStats service")
    patch_sso_add_user_to_group()
    modified_config_file = Path(vstats_config_file_path + suffix)
    if modified_config_file.is_file():
        shutil.copy(vstats_config_file_path + suffix, vstats_config_file_new_path)
    elif Path(vstats_config_file_path).is_file():
        shutil.copy(vstats_config_file_path, vstats_config_file_new_path)

def is_patch_needed(current_version):
    return utils.is_patch_needed(current_version, PATCH_VERSION)

def doExpand(ctx):
    logger.info("No expand required for version 4 on vstats service")

def doContract(ctx):
    logger.info("No contract required for version 4 on vstats service")
