#!/opt/cloudlinux/venv/bin/python3 -bb
# -*- coding: utf-8 -*-

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

'''

This script used to add lve exention to existing cpanel package with default values

'''
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

from future.utils import iteritems

import sys

import cldetectlib as detect
import lvectllib

from clcommon import page_to_memory
from clcommon.cpapi import admin_packages
from clcommon.cpapi.cpapiexceptions import CPAPIExternalProgramFailed
from clcommon.lib.whmapi_lib import WhmApiRequest, WhmApiError
from clhooklib import log_error, check_cpanel_version


SCRIPT_NAME = 'cl_modify_pkg'
LVE_EXT = 'lve'
DEF_LIMIT = 'DEFAULT'


def check_lve_ext_in_package(package):
    '''
    Check lve extention in package
    return True - if found
           False - if not found
    '''
    try:
        pkg_exts = WhmApiRequest('getpkginfo') \
            .with_arguments(pkg=package) \
            .call() \
            ['pkg']['_PACKAGE_EXTENSIONS']
    except WhmApiError as e:
        log_error(SCRIPT_NAME, 'Can\'t get package info for package ' + package)
        return True
    ext_list = pkg_exts.split()
    if LVE_EXT in ext_list:
        return True
    return False

def check_limit(limit, el):
    '''
    Check limits in package

    return limit from package if exist; default limits if not
    '''
    try:
        l = el.getElementsByTagName(limit)[0].getAttribute('limit')
    except IndexError:
        return DEF_LIMIT
    if l == '':
        return DEF_LIMIT
    return str(l)


def get_pkg_limits(package):
    '''
    Get package limits from /etc/container/ve.cfg

    return dict
    '''
    lve_dict = {
        'lve_cpu': 'cpu',
        'lve_io': 'io',
        'lve_ep': 'ep',
        'lve_nproc': 'nproc',
        'lve_iops': 'iops',
    }
    lve_mem_dict = {
        'lve_mem': 'mem',
        'lve_pmem': 'pmem',
    }
    setup_data = {}
    lvectllib.init()
    lvectllib.get_XML_cfg()
    for el in lvectllib.ve_package:
        if (str(el.getAttribute('id')) == package):
            # Get all lve limits except memory
            for lve_key, lve_val in iteritems(lve_dict):
                setup_data[lve_key] = check_limit(lve_val, el)
            # Get lve memory limits
            for lve_mkey, lve_mval in iteritems(lve_mem_dict):
                lve_mem_val = check_limit(lve_mval, el)
                if lve_mem_val == DEF_LIMIT:
                    setup_data[lve_mkey] = lve_mem_val
                else:
                    setup_data[lve_mkey] = str(page_to_memory(int(lve_mem_val)))
    return setup_data


def add_lve_in_package(package):
    '''
    Add lve extention in cpanel package
    return nothing
    '''
    # Do nothing if lve already present
    if check_lve_ext_in_package(package):
        return
    # Get current lve limits
    pkg_limits = get_pkg_limits(package)
    # addpkgext function updates extensions
    # Input: extension and extension limits
    # Apply default if pkg_limits == {}
    try:
        WhmApiRequest('addpkgext') \
            .with_arguments(name=package,
                            _PACKAGE_EXTENSIONS=LVE_EXT,
                            **pkg_limits) \
            .call()
    except WhmApiError as e:
        log_error(SCRIPT_NAME, 'Package ' + package + ' hasn\'t modify')


if detect.is_cpanel():
    if check_cpanel_version():
        try:
            # Get only root pkgs, without resellers pkgs
            packages = admin_packages(raise_exc=True)
        except (OSError, CPAPIExternalProgramFailed):
            log_error(SCRIPT_NAME, 'Can\'t get package list')
            sys.exit(1)
        for package in packages:
            add_lve_in_package(package)
