#!/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

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys
from shutil import copy

import cldetectlib as detect
from clcommon.const import Feature
from clcommon.cpapi import is_panel_feature_supported
from clcommon.utils import mod_makedirs
from clhooklib import log_error, check_cpanel_version


CPANEL_EXTENSIONS_DIR = '/var/cpanel/packages/extensions'
SOURCE_PATH = '/usr/share/l.v.e-manager/'
SCRIPT_NAME = 'install_lve_tmp.py'
VE_CFG_PATH = '/etc/container/ve.cfg'


ALL_LVE_SETTINGS = (
    'lve_ncpu',
    'lve_cpu',
    'lve_ep',
    'lve_io',
    'lve_mem',
    'lve_pmem',
    'lve_nproc',
    'lve_iops',
    'lve_inodes_soft',
    'lve_inodes_hard',
    'lve_mysql_cpu',
    'lve_mysql_io',
)


INODES_LVE_SETTINGS = (
    'lve_inodes_soft',
    'lve_inodes_hard',
)


if detect.is_cpanel() and check_cpanel_version():
    if not os.path.lexists(CPANEL_EXTENSIONS_DIR):
        mod_makedirs(CPANEL_EXTENSIONS_DIR, 0o700)

    is_lve_suppported = is_panel_feature_supported(Feature.LVE)
    if is_lve_suppported and os.path.isfile(SOURCE_PATH + 'cpanel/extension/lve.tt2'):
        copy(SOURCE_PATH + 'cpanel/extension/lve.tt2', CPANEL_EXTENSIONS_DIR + '/lve.tt2')
    elif not is_lve_suppported and os.path.isfile(SOURCE_PATH + 'cpanel/extension/lve_inodes_only.tt2'):
        copy(SOURCE_PATH + 'cpanel/extension/lve_inodes_only.tt2', CPANEL_EXTENSIONS_DIR + '/lve.tt2')

    try:
        with open(CPANEL_EXTENSIONS_DIR + '/lve', 'w') as f:
            f.write('_NAME=LVE Settings'+'\n')
            lve_settings = ALL_LVE_SETTINGS if is_lve_suppported else INODES_LVE_SETTINGS
            f.writelines([f'{p}=DEFAULT\n' for p in lve_settings])
    except OSError:
        log_error(SCRIPT_NAME, 'Can\'t write LVE settings to default extension file')
        sys.exit(1)
