# Copyright (c) 2021 VMware, Inc.  All rights reserved. -- VMware Confidential
import json
import logging
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), "../../../../../install/py-modules/"))

from wcpconfigure import LocalOsUser, _WCPSVC_OS_USER

sys.path.append(os.path.join(os.path.dirname(__file__), "../"))

from utils import CONFIG_DIR

logger = logging.getLogger(__name__)

CHANGELOG = ["Change the ownership of files and directories to wcp local os user so that wcp service can access them"]
CONFIGURATION_FILE_MANIFEST_NAME = "wcp-configuration-manifest.json"


def change_config_files_owner():
    # Post upgrade to a version when wcp service will run as non-root user,
    # wcpsvc will fail to read/write certain configuration files/directories
    # because they are still owned by root. Transfer ownership of files/directories
    # mentioned in manifest file to wcp local os user to allow wcp startup as non-root user.
    with open(os.path.join(CONFIG_DIR, CONFIGURATION_FILE_MANIFEST_NAME), 'r') as f:
        config = json.load(f)
        local_os_user = LocalOsUser(_WCPSVC_OS_USER)
        for directory in config["directories"]:
            try:
                local_os_user.change_owner_group(directory["path"], recursive=directory["recursive"])
            except FileNotFoundError as error:
                logging.warning("Cannot find directory %s. Change ownership to %s is skipped. Err: %s.", directory["path"], _WCPSVC_OS_USER, error)
        for file in config["files"]:
            try:
                local_os_user.change_owner_group(file)
            except FileNotFoundError as error:
                logging.warning("Cannot find file %s. Change ownership to %s is skipped. Err: %s.", file, _WCPSVC_OS_USER, error)


def doPatchingWithDependencies():
    # The ownership change must be executed before starting wcp
    # Also change the ownership here because NDU/RDU do not apply patches
    # in doPatchingWithoutDependencies
    change_config_files_owner()


def doPatchingWithoutDependencies():
    # doPatchingWithoutDependencies is executed before services that wcpsvc
    # depends on are started.
    # The ownership change must be executed before starting wcp
    change_config_files_owner()


def getChanges():
    return '%s: Changelog:\n%s' % (
        os.path.basename(__file__),
        '\n'.join(['* ' + line for line in CHANGELOG]))
