# -*- coding: utf-8 -*-

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2021 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import absolute_import
import os
import re
import json
from exec_command import exec_command

SOURCE_PATH = "/usr/share/l.v.e-manager/"
FEATURES_PATH = '/usr/local/cpanel/whostmgr/addonfeatures/'

def cpanel_fix_feature_manager(pathes_to_installs):
    """
    Fix displaying of plugins in cPanel Feature Manager
    :param pathes_to_installs: list
    :return: None
    """
    for path in pathes_to_installs:
        if os.path.exists(FEATURES_PATH):
            with open(SOURCE_PATH + path) as feature_file:
                features = json.load(feature_file)
                cpanel_fix_feature_files(features)
    exec_command(SOURCE_PATH + 'cpanel/utils/dynamicuictl.py --hide=enduserlve,cpu_and_concurrent_connection_usage')

def cpanel_fix_feature_files(features):
    """
    Fix feature files
    :param features: list
    :return: None
    """
    for feature in features:
        feature_file = open(FEATURES_PATH + feature['feature'], 'w')
        feature_name = feature['name']
        try:
            feature_name_fixed = re.search("\$LANG{'(.*)'}", feature_name).group(1)
        except AttributeError:
            feature_name_fixed = ''
        feature_file.write(feature['feature'] + ':' + feature_name_fixed)
        feature_file.close()

def cpanel_remove_from_feature_list(features):
    """
    Remove plugin from cPanel Feature List
    :param features: list
    :return: None
    """
    for feature in features:
        feature_file = FEATURES_PATH + feature
        if os.path.isfile(feature_file):
            os.remove(feature_file)
