MMCT TEAM
Server IP : 103.53.40.154  /  Your IP : 3.131.13.24
Web Server : Apache
System : Linux md-in-35.webhostbox.net 4.19.286-203.ELK.el7.x86_64 #1 SMP Wed Jun 14 04:33:55 CDT 2023 x86_64
User : ppcad7no ( 715)
PHP Version : 8.2.25
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON
Directory (0555) :  /bin/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : //bin/switch_mod_lsapi
#!/usr/bin/python3

#%copyright%

import os
import sys
import getopt
import shutil
import hashlib
import time
from packaging.version import Version

# pylint: disable=wrong-import-position
sys.path.append(os.path.abspath("/usr/share/lve/modlscapi/user"))
import mod_lsapi_stat
from stat_utils import plesk_bin_php_handler
from lve_diagnostic import  get_cp
from exec_command import exec_command, exec_command_out
def is_ubuntu():
    return False

SOURCE = "/usr/share/lve/modlscapi/user"
ENABLED_FILE = "/usr/share/lve/modlscapi/global.enabled"
CUSTOM_PANEL_SRC = "/usr/share/lve/modlscapi/custom/"


def touch(fname):
    try:
        os.utime(fname, None)
    except:
        open(fname, 'a').close()


def get_cl_num():
    result = exec_command("rpm -q --qf \"%{version}\n\" `rpm -q --whatprovides /etc/redhat-release`")
    return result[0] if result else '8'

def add_one_item_to_php_handler(path, needle):
    """
    Add one configuration string to php.handler
    """
    with open(path, "a+") as file:
        for line in file:
            if needle in line:
                break
        else:  # not found, we are at the eof
            file.write("%s\n" % needle)  # append missing data


def add_lines(path, lines):
    """
    Add lines to file
    """
    for line in lines:
        add_one_item_to_php_handler(path, line.strip())


def remove_all_lines(path, lines):
    """
    Remove lines from file
    """
    for line in lines:
        exec_command_out(
            """sed -i -e '/^[[:space:]]*%s[[:space:]]*$/d' %s""" % (line.strip().replace("/", "\\/"), path))


def getItem(txt1, txt2, op):
    try:
        i1 = int(txt1)
    except ValueError:
        i1 = -1
    try:
        i2 = int(txt2)
    except ValueError:
        i2 = -1
    if i1 == -1 or i2 == -1:
        if op == 0:
            return txt1 > txt2
        else:
            return txt1 < txt2
    else:
        if op == 0:
            return i1 > i2
        else:
            return i1 < i2


# Compare version of types xx.xx.xxx... and yyy.yy.yy.y..
# if xxx and yyy is numbers, than comapre as numbers
# else - comapre as strings
def verCompare(base, test):
    base = base.split(".")
    test = test.split(".")
    if (len(base) > len(test)):
        ln = len(test)
    else:
        ln = len(base)
    for i in range(ln):
        if getItem(base[i], test[i], 0):
            return 1
        if getItem(base[i], test[i], 1):
            return -1
    if len(base) == len(test):
        return 0
    elif len(base) > len(test):
        return 1
    else:
        return 0


def usage():
    print('')
    print('Use the following syntax to manage the mod_lsapi install tool:')
    print(sys.argv[0] + " [OPTIONS]")
    print('Options:')
    print("--setup - setup mod_lsapi configurations for Apache")
    print("--setup-light - only setup the EasyApache 4 feature")
    print("--uninstall - uninstall mod_lsapi from Apache")
    print("--enable-domain - enable mod_lsapi for an individual domain")
    print("--disable-domain - disable mod_lsapi for an individual domain")
    print("--enable-global - sets up mod_lsapi as a default way to serve PHP, making it enabled for all domains. Once that mode is enabled, you cannot disable mod_lsapi for individual domains")
    print("--disable-global - disable mod_lsapi as a default way to serve PHP, disabling mod_lsapi for all domains, including those selected previously using --enable-domain")
    print("--build-native-lsphp - build native lsphp for cPanel")
    print("--build-native-lsphp-cust - build native lsphp for cPanel (with custom PHP source path)")
    print("--check-php - check PHP configuration")
    print("--verbose - switch verbose logging on")
    print("--force - only with setup option (EA4)")
    print("--stat - return statistics in JSON")


PLESK_PHP_HANDLERS = {
    "x-httpd-lsphp-44": {
        'path': "/opt/alt/php44/usr/bin/lsphp",
        'name': "LSPHP4.4 alt-php",
        'phpini': "/opt/alt/php44/etc/php.ini",
        'cli': "/opt/alt/php44/usr/bin/php"
    },
    "x-httpd-lsphp-51": {
        'path': "/opt/alt/php51/usr/bin/lsphp",
        'name': "LSPHP5.1 alt-php",
        'phpini': "/opt/alt/php51/etc/php.ini",
        'cli': "/opt/alt/php51/usr/bin/php"
    },
    "x-httpd-lsphp-52": {
        'path': "/opt/alt/php52/usr/bin/lsphp",
        'name': "LSPHP5.2 alt-php",
        'phpini': "/opt/alt/php52/etc/php.ini",
        'cli': "/opt/alt/php52/usr/bin/php"
    },
    "x-httpd-lsphp-53": {
        'path': "/opt/alt/php53/usr/bin/lsphp",
        'name': "LSPHP5.3 alt-php",
        'phpini': "/opt/alt/php53/etc/php.ini",
        'cli': "/opt/alt/php53/usr/bin/php"
    },
    "x-httpd-lsphp-54": {
        'path': "/opt/alt/php54/usr/bin/lsphp",
        'name': "LSPHP5.4 alt-php",
        'phpini': "/opt/alt/php54/etc/php.ini",
        'cli': "/opt/alt/php54/usr/bin/php"
    },
    "x-httpd-lsphp-55": {
        'path': "/opt/alt/php55/usr/bin/lsphp",
        'name': "LSPHP5.5 alt-php",
        'phpini': "/opt/alt/php55/etc/php.ini",
        'cli': "/opt/alt/php55/usr/bin/php"
    },
    "x-httpd-lsphp-56": {
        'path': "/opt/alt/php56/usr/bin/lsphp",
        'name': "LSPHP5.6 alt-php",
        'phpini': "/opt/alt/php56/etc/php.ini",
        'cli': "/opt/alt/php56/usr/bin/php"
    },
    "x-httpd-lsphp-70": {
        'path': "/opt/alt/php70/usr/bin/lsphp",
        'name': "LSPHP7.0 alt-php",
        'phpini': "/opt/alt/php70/etc/php.ini",
        'cli': "/opt/alt/php70/usr/bin/php"
    },
    "x-httpd-lsphp-71": {
        'path': "/opt/alt/php71/usr/bin/lsphp",
        'name': "LSPHP7.1 alt-php",
        'phpini': "/opt/alt/php71/etc/php.ini",
        'cli': "/opt/alt/php71/usr/bin/php"
    },
    "x-httpd-lsphp-72": {
        'path': "/opt/alt/php72/usr/bin/lsphp",
        'name': "LSPHP7.2 alt-php",
        'phpini': "/opt/alt/php72/etc/php.ini",
        'cli': "/opt/alt/php72/usr/bin/php"
    },
    "x-httpd-lsphp-73": {
        'path': "/opt/alt/php73/usr/bin/lsphp",
        'name': "LSPHP7.3 alt-php",
        'phpini': "/opt/alt/php73/etc/php.ini",
        'cli': "/opt/alt/php73/usr/bin/php"
    },
    "x-httpd-lsphp-74": {
        'path': "/opt/alt/php74/usr/bin/lsphp",
        'name': "LSPHP7.4 alt-php",
        'phpini': "/opt/alt/php74/etc/php.ini",
        'cli': "/opt/alt/php74/usr/bin/php"
    },
    "x-httpd-lsphp-80": {
        'path': "/opt/alt/php80/usr/bin/lsphp",
        'name': "LSPHP8.0 alt-php",
        'phpini': "/opt/alt/php80/etc/php.ini",
        'cli': "/opt/alt/php80/usr/bin/php"
    },
    "x-httpd-lsphp-81": {
        'path': "/opt/alt/php81/usr/bin/lsphp",
        'name': "LSPHP8.1 alt-php",
        'phpini': "/opt/alt/php81/etc/php.ini",
        'cli': "/opt/alt/php81/usr/bin/php"
    },
    "x-httpd-lsphp-82": {
        'path': "/opt/alt/php82/usr/bin/lsphp",
        'name': "LSPHP8.2 alt-php",
        'phpini': "/opt/alt/php82/etc/php.ini",
        'cli': "/opt/alt/php82/usr/bin/php"
    },
    "x-httpd-lsphp-83": {
        'path': "/opt/alt/php83/usr/bin/lsphp",
        'name': "LSPHP8.3 alt-php",
        'phpini': "/opt/alt/php83/etc/php.ini",
        'cli': "/opt/alt/php83/usr/bin/php"
    },
    "x-httpd-lsphp-custom": {
        'path': "/usr/local/bin/lsphp",
        'name': "LSPHP by vendor OS",
        'phpini': "/etc/php.ini",
        'cli': "/usr/bin/php"
    }
}
PLESK_DEFAULT_DOMAIN = '/usr/local/psa/admin/conf/templates/default/domain/domainVirtualHost.php'
PLESK_CUSTOM_DOMAIN = '/usr/local/psa/admin/conf/templates/custom/domain/domainVirtualHost.php'


def plesk_save_default_domain_hash():
    with open('/usr/share/lve/modlscapi/plesk_domain_md5', 'w') as md5sum:
        md5sum.write(hashlib.md5(open(PLESK_DEFAULT_DOMAIN, 'rb').read()).hexdigest())


def plesk_remove_hook(script_name='/usr/share/lve/modlscapi/hooks/plesk_update_hook.py'):
    """
    Event handler removal based on script name (containing into 'Command' field)
    :param script_name: hook script to remove from handlers
    """
    # remove md5sum storage file and hook log
    for f in ('/usr/share/lve/modlscapi/plesk_domain_md5',
              '/usr/share/lve/modlscapi/plesk_upd_hook.log'):
        if os.path.exists(f):
            os.unlink(f)
    # find and remove hook
    all_hooks = exec_command('plesk bin event_handler -l')
    current_id = None
    for l in all_hooks:
        if not l:
            continue
        try:
            k, v = l.split()
        except ValueError:
            continue
        if k == 'Id':
            current_id = v
        elif current_id is not None and v == script_name:
            exec_command_out('plesk bin event_handler -d {0}'.format(current_id))
            current_id = None


def plesk_get_installed_handlers():
    """
    Get installed handlers list
    :return: list of IDs of installed handlers
    """
    installed_handlers = plesk_bin_php_handler('list')
    return [x['id'] for x in installed_handlers]


def plesk_install():
    """
    Install mod_lsapi to plesk
    """
    install_default_handler = 0

    if not os.path.isdir(os.path.dirname(PLESK_CUSTOM_DOMAIN)):
        os.makedirs(os.path.dirname(PLESK_CUSTOM_DOMAIN))
    if os.path.exists(PLESK_DEFAULT_DOMAIN):
        plesk_save_default_domain_hash()
        if os.path.exists(PLESK_CUSTOM_DOMAIN):
            os.remove(PLESK_CUSTOM_DOMAIN)
        shutil.copy(PLESK_DEFAULT_DOMAIN, PLESK_CUSTOM_DOMAIN)
        exec_command_out("patch {f} {path}/domainVirtualHost.php.patch".format(f=PLESK_CUSTOM_DOMAIN, path=SOURCE))

    if not os.path.isdir("/usr/local/psa/admin/conf/templates/custom/service/"):
        os.makedirs("/usr/local/psa/admin/conf/templates/custom/service/")
    shutil.copy(SOURCE + "/php_over_lsphp.php", "/usr/local/psa/admin/conf/"
                                                "templates/custom/service/php_over_lsphp.php")

    if not os.path.exists('/etc/container'):
        os.mkdir('/etc/container')
    add_lines("/etc/container/php.handler",
              ["{0} {1}".format(key, PLESK_PHP_HANDLERS[key]['path']) for key in PLESK_PHP_HANDLERS])

    if os.path.exists("/opt/alt/php56/usr/bin/lsphp"):
        if os.path.exists("/usr/local/bin/lsphp"):
            os.remove("/usr/local/bin/lsphp")
        shutil.copy("/opt/alt/php56/usr/bin/lsphp", "/usr/local/bin/lsphp")
        install_default_handler = 1

    tmpl_add = """/usr/local/psa/bin/php_handler --add -displayname "%(name)s" -path %(path)s -phpini %(ini)s -clipath %(cli)s -type fastcgi -id %(id)s"""
    tmpl_update = """/usr/local/psa/bin/php_handler --update -id %(id)s -type fastcgi"""

    if install_default_handler != 0 and 'x-httpd-lsphp-custom' not in plesk_get_installed_handlers():
        # install and update default handler
        exec_command_out(
            tmpl_add % {'id': 'x-httpd-lsphp-custom',
                        'name': PLESK_PHP_HANDLERS['x-httpd-lsphp-custom']['name'],
                        'path': PLESK_PHP_HANDLERS['x-httpd-lsphp-custom']['path'],
                        'ini': PLESK_PHP_HANDLERS['x-httpd-lsphp-custom']['phpini'],
                        'cli': PLESK_PHP_HANDLERS['x-httpd-lsphp-custom']['cli']}
        )
        exec_command_out(tmpl_update % {'id': 'x-httpd-lsphp-custom'})

    # install other handlers
    for key in set(PLESK_PHP_HANDLERS.keys()).difference(set(plesk_get_installed_handlers())):
        tmpl_add_parameters = {'id': key,
                               'name': PLESK_PHP_HANDLERS[key]['name'],
                               'path': PLESK_PHP_HANDLERS[key]['path'],
                               'ini': PLESK_PHP_HANDLERS[key]['phpini'],
                               'cli': PLESK_PHP_HANDLERS[key]['cli']}
        #In case of failure, try several times:
        for i in range(5):
            if exec_command_out(tmpl_add % tmpl_add_parameters):
                time.sleep(3)
            else:
                break
        exec_command_out(tmpl_update % {'id': key})

    exec_command_out("""/usr/local/psa/admin/sbin/httpdmng --reconfigure-all""")

    exec_command_out("service httpd restart")

    return 0


def plesk_uninstall():
    """
    Uninstall mod_lsapi from plesk
    """

    print(bcolors.WARNING + "Uninstalling Plesk LSPHP handlers" + bcolors.ENDC)

    tmpl_remove = "/usr/local/psa/bin/php_handler --remove -id %(id)s"
    for key in PLESK_PHP_HANDLERS:
        exec_command_out(tmpl_remove % {'id': key})

    if os.path.exists("/usr/local/bin/lsphp"):
        os.remove("/usr/local/bin/lsphp")

    remove_all_lines("/etc/container/php.handler",
                     ["{} {}".format(key, PLESK_PHP_HANDLERS[key]['path']) for key in PLESK_PHP_HANDLERS])

    plesk_remove_hook()

    return 0


class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''


def install_modlsapi():
    if is_ubuntu() and cp.name == "Unknown CP":
        if os.path.exists('/usr/sbin/cagefsctl'):
            if not os.path.exists('/usr/local/bin/lsphp'):
                try:
                    os.symlink('/opt/alt/php74/usr/bin/lsphp', '/usr/local/bin/lsphp')
                except OSError:
                    pass
                exec_command_out('cagefsctl --force-update')

        exec_command_out('a2enmod lsapi')
        print("Restarting apache2 service...")
        exec_command('systemctl restart apache2')
    elif cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if verCompare(cp.version, "12.5") >= 0:
            plesk_install()
        else:
            exec_command_out(SOURCE + "/rpm_install")
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if verbose_level > 0:
            if force_opt > 0:
                exec_command_out(SOURCE + "/switch_lsapi --verbose --force --setup")
            else:
                exec_command_out(SOURCE + "/switch_lsapi --verbose --setup")
        else:
            if force_opt > 0:
                exec_command_out(SOURCE + "/switch_lsapi --force --setup")
            else:
                exec_command_out(SOURCE + "/switch_lsapi --setup")
        touch("/var/cpanel/easy_skip_update_php_mime_types")
    elif cp.name == "InterWorx":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        exec_command_out(SOURCE + "/rpm_install")
    elif cp.name == "ISPManager":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        exec_command_out(SOURCE + "/rpm_install")
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + cp.doc_url + bcolors.ENDC)
        __command = CUSTOM_PANEL_SRC + cp.executable + " --setup"
        if force_opt:
            __command += ' --force'
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')

    else:
        if Version(get_cl_num()) < Version('6'):
            print(bcolors.WARNING + "CloudLinux Version 5 without panels is not supported!!!" + bcolors.ENDC)
        else:
            print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
            __command = SOURCE + "/rpm_install"
            print(f'Running command for a no-panel installation: {__command}')
            return_code = exec_command_out(__command)
            if verbose_level:
                print(f'Command: {__command} exited with code {return_code}')

def uninstall_modlsapi():
    if is_ubuntu() and cp.name == "Unknown CP":
        exec_command_out("a2dismod lsapi")
        print("Restarting apache2 service ...")
        exec_command_out("systemctl restart apache2")
    elif cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        if verCompare(cp.version, "12.5") >= 0:
            plesk_uninstall()
        else:
            print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if os.path.exists("/var/cpanel/easy_skip_update_php_mime_types"):
            os.remove("/var/cpanel/easy_skip_update_php_mime_types")
        if verbose_level > 0:
            exec_command_out(SOURCE + "/switch_lsapi --verbose --uninstall")
        else:
            exec_command_out(SOURCE + "/switch_lsapi --uninstall")
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        __command = CUSTOM_PANEL_SRC + cp.executable + " --uninstall"
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')
    else:
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)
    if os.path.exists(ENABLED_FILE):
        os.remove(ENABLED_FILE)


def enable_domain_modlsapi(a):
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if verbose_level > 0:
            exec_command_out(SOURCE + "/switch_lsapi --verbose --enable-domain " + a)
        else:
            exec_command_out(SOURCE + "/switch_lsapi --enable-domain " + a)
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        __command = CUSTOM_PANEL_SRC + cp.executable + " --enable-domain " + a
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')
    else:
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def disable_domain_modlsapi(a):
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if verbose_level > 0:
            exec_command_out(SOURCE + "/switch_lsapi --verbose --disable-domain " + a)
        else:
            exec_command_out(SOURCE + "/switch_lsapi --disable-domain " + a)
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        __command = CUSTOM_PANEL_SRC + cp.executable + " --disable-domain " + a
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')
    else:
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def enable_global_modlsapi():
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if force_opt > 0:
            if verbose_level > 0:
                exec_command_out(SOURCE + "/switch_lsapi --verbose --force --enable-global")
            else:
                exec_command_out(SOURCE + "/switch_lsapi --force --enable-global")
        else:
            if verbose_level > 0:
                exec_command_out(SOURCE + "/switch_lsapi --verbose --enable-global")
            else:
                exec_command_out(SOURCE + "/switch_lsapi --enable-global")
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        __command = CUSTOM_PANEL_SRC + cp.executable + " --enable-global"
        if force_opt > 0:
            __command += ' --force'
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')
    else:
        if is_ubuntu():
            exec_command_out('a2dismod suphp proxy_fcgi php7.4')
            print("Restarting apache service ...")
            exec_command_out('systemctl restart apache2')
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def disable_global_modlsapi():
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        if verbose_level > 0:
            exec_command_out(SOURCE + "/switch_lsapi --verbose --disable-global")
        else:
            exec_command_out(SOURCE + "/switch_lsapi --disable-global")
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        __command = CUSTOM_PANEL_SRC + cp.executable + " --disable-global"
        if verbose_level:
            __command += ' --verbose'
            print(f'Calling command for panel {cp.panel_name}: {__command}')

        return_code = exec_command_out(__command)
        if verbose_level:
            print(f'Command: {__command} for panel {cp.panel_name} exited with code {return_code}')
    else:
        if is_ubuntu():
            exec_command_out('a2enmod suphp proxy_fcgi php7.4')
            print("Restarting apache service ...")
            exec_command_out('systemctl restart apache2')
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def lsphp_modlsapi(a):
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        print(bcolors.OKGREEN + "Instruction: " + bcolors.OKBLUE + "http://docs.cloudlinux.com/index.html?apache_mod_lsapi.html" + bcolors.ENDC)
        exec_command_out(SOURCE + "/switch_lsapi --build-native-lsphp " + a)
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    else:
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def setup_light():
    if cp.name == "Plesk" and verCompare(cp.version, "10") >= 0:
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "cPanel":
        if verbose_level > 0:
            exec_command_out(SOURCE + "/switch_lsapi --verbose --setup-light ")
        else:
            exec_command_out(SOURCE + "/switch_lsapi --setup-light ")
    elif cp.name == "InterWorx":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "ISPManager":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "DirectAdmin":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    elif cp.name == "CustomPanel":
        print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
    else:
        print(bcolors.FAIL + "!!!Unknown panel!!!!" + bcolors.ENDC)


def check_php():
    """
    Check php configurations
    """
    exec_command_out(SOURCE + "/lsphpchecker.py fast")


verbose_level = 0
force_opt = 0

cp = get_cp()
try:
    opts, args = getopt.getopt(sys.argv[1:], "h",
                               ["help", "setup", "setup-light", "force", "enable-domain=", "disable-domain=",
                                "enable-global", "disable-global", "uninstall", "build-native-lsphp",
                                "build-native-lsphp-cust=", "check-php", "verbose", "stat"])
except getopt.GetoptError as err:
    # print help information and exit:
    print(str(err))  # will print something like "option -a not recognized"
    usage()
    sys.exit(2)

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("--verbose",):
        verbose_level = 1
    elif o in ("--force"):
        force_opt = 1
    elif o in ("--setup",):
        install_modlsapi()
    elif o in ("--setup-light"):
        setup_light()
    elif o in ("--enable-domain",):
        enable_domain_modlsapi(a)
    elif o in ("--disable-domain",):
        disable_domain_modlsapi(a)
    elif o in ("--enable-global",):
        enable_global_modlsapi()
    elif o in ("--disable-global",):
        disable_global_modlsapi()
    elif o in ("--uninstall",):
        uninstall_modlsapi()
    elif o in ("--build-native-lsphp",):
        lsphp_modlsapi("")
    elif o in ("--build-native-lsphp-cust",):
        lsphp_modlsapi(a)
    elif o in ("--check-php",):
        if cp.name == "CustomPanel":
            print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
            exit(0)
        check_php()
    elif o in ("--stat",):
        if cp.name == "CustomPanel":
            print(bcolors.WARNING + "!!!Not supported yet!!!" + bcolors.ENDC)
            exit(0)
        print(mod_lsapi_stat.get(as_json=True))
    else:
        usage()
        sys.exit(2)

MMCT - 2023