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

import cldetectlib as detect
import os
from shutil import copy

from clcommon.public_hooks import setup_logger_and_sentry
from clcommon.public_hooks.bundle import cpanel
from clcommon.utils import mod_makedirs
from clhooklib import (
    check_cpanel_version,
    VERIFY_HOOK,
    VERIFY_HOOK_SCRIPTS,
    SOURCE_PATH,
    LVE_EXTENSION_HOOKS,
    # LVEMAN-970
    # check_result
)
from clcommon.lib.cledition import lve_supported_or_exit

SCRIPT_NAME = os.path.basename(__file__)
CPANEL_EXTENSIONS_DIR = '/var/cpanel/packages/extensions'
VE_CFG_PATH = '/etc/container/ve.cfg'
CPANEL_DOCROOT = '/usr/local/cpanel/whostmgr/docroot/3rdparty/cloudlinux'


@lve_supported_or_exit  # temporary disabled until CLPRO-2013 is done
def main():
    # in fact this is only wrapper for
    # hooks logic located in cllib
    # so we can just use cllib sentry here
    setup_logger_and_sentry()

    if detect.is_cpanel() and check_cpanel_version('63.9999'):
        if not os.path.lexists(CPANEL_EXTENSIONS_DIR):
            mod_makedirs(CPANEL_EXTENSIONS_DIR, 0o700)
        subprocess.run(SOURCE_PATH + 'cpanel/extension/install_lve_tmp.py', shell=True, executable='/bin/bash')
        if os.path.isfile(SOURCE_PATH + 'cpanel/extension/lve_ext_scritps.js'):
            if not os.path.exists(CPANEL_DOCROOT):
                os.makedirs(CPANEL_DOCROOT)
            copy(SOURCE_PATH + 'cpanel/extension/lve_ext_scritps.js',
                 CPANEL_DOCROOT + '/lve_ext_scritps.js')

        #        if os.path.isfile(SOURCE_PATH + 'cpanel/extension/cl_modify_pkg.py'):
        #            # LVEMAN-970 Adding lve extension to packages
        #            # using cpanel api funtion addpkgext
        #            result = subprocess.call(SOURCE_PATH + 'cpanel/extension/cl_modify_pkg.py',
        #            shell=True, executable='/bin/bash')
        #            check_result(result, SCRIPT_NAME, 'Can\'t add extension to some packages')

        if os.path.isfile(VERIFY_HOOK):
            copy(VERIFY_HOOK, VERIFY_HOOK_SCRIPTS)
            cpanel.install_hooks(LVE_EXTENSION_HOOKS)


if __name__ == '__main__':
    main()
