\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7<F<2PFAFZUP_xxnnx\F5\AF\B9\91\C8\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\DB\00CUZZxix‚\EB\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\C0\00\00b\00d\00\FF\C4\00\00\00\00\00\00\00\00\00\00\00\00\00\00\FF\C4\00\00\00\00\00\00\00\00\00\00\001A!Q\FF\C4\00\00\00\00\00\00\00\00\00\00\00\00\00\FF\C4\00\00\00\00\00\00\00\00\00\00!1AQ\FF\DA\00\00\00?\00\F6\00\00\00\00\00\00\00\00\00\00\A0\00\00\C5\CF\F8\E7Ó\FCjD~\B9^\AD\%\B3]\D8cs-\BBs,-\A0\00"\80\00%\B83rÏ^K~F\A4ea\00E\00\C6\EE=u\B1\9B\D1\00@\00r\BE8\F9:\FE5#.M\00\E7\CB\C9q\CBq\D6\F2\BE\B7\C7>\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7	\8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh
\00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€
\00$\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95
59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>C///</title>
</head>
#!/usr/bin/env python
# -*- mode:python; coding:utf-8; -*-
# author: Dmitriy Kasyanov <dkasyanov@cloudlinux.com>

import getopt
import glob
import logging
import os
import sys
import traceback
try:
        import configparser
except ImportError:
        import ConfigParser as configparser

try:
    import rpm
except:
    class rpm:
        @staticmethod
        def labelCompare(version1, version2):
            def index_exists(_list, i):
                return (0 <= i < len(_list)) or (-len(_list) <= i < 0)

            res = 0
            ver1 = version1[1].split('.')
            ver2 = version2[1].split('.')
            max_num = len(ver1)
            if len(ver2) > max_num:
                max_num = len(ver2)
            i = 0
            while i < max_num:
                if index_exists(ver1,i) and index_exists(ver2,i):
                    if ver1[i] == ver2[i]:
                        res=0
                    else:
                        return int(ver1[i]) - int(ver2[i])
                elif index_exists(ver1,i) and not index_exists(ver2,i):
                    return 1
                elif index_exists(ver2,i) and not index_exists(ver1,i):
                    return -1
                i += 1
            return 0

# Minimal version with MultiPHP support for alt-php
MIN_CPANEL_VERSION = '11.66.0.11'
SCL_PREFIX_PATH = '/etc/scl/prefixes'
CONFIG_PATH = '/opt/alt/alt-php-config/alt-php.cfg'


def configure_logging(verbose):
    """
    Logging configuration function.

    @type verbose:  bool
    @param verbose: Enable additional debug output if True, display only errors
        otherwise.
    """
    if verbose:
        level = logging.DEBUG
    else:
        level = logging.ERROR
    handler = logging.StreamHandler()
    handler.setLevel(level)
    log_format = "%(levelname)-8s: %(message)s"
    formatter = logging.Formatter(log_format, "%H:%M:%S %d.%m.%y")
    handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.addHandler(handler)
    logger.setLevel(level)
    return logger


def get_cpanel_version():
    """
    Returns cPanel version if cPanel installed or None othervise.

    @rtype: str or None
    @return: String with cPanel version or None if cPanel not installed.
    """
    if os.path.exists('/usr/local/cpanel/version'):
        with open('/usr/local/cpanel/version', 'r') as fd:
            version = fd.read()
            return version
    return None


def find_interpreter_versions():
    """
    Returns list of installed alt-php versions and their base directories.

    @rtype:  list
    @return: List of version (e.g. 44, 55) and base directory tuples.
    """
    int_versions = []
    base_path_regex = "/opt/alt/php[0-9][0-9]"
    for int_dir in glob.glob(base_path_regex):
        if os.path.exists(os.path.join(int_dir, "usr/bin/php")):
            int_versions.append((int_dir[-2:], int_dir))
    int_versions.sort()
    return int_versions


def delete_prefix(prefix_path):
    """
    Remove prefix file
    @type prefix_path: str
    @param prefix_path: Path to the prefix file, e.g. /etc/scl/prefix/alt-php70

    @rtype: bool
    @return: True if file was removed sucessfully, False otherwise
    """
    try:
        if os.path.exists(prefix_path):
            os.unlink(prefix_path)
        return True
    except OSError as e:
        logging.error(u"Couldn't remove prefix %s:\n%s" % (prefix_path, e))
        return False


def create_prefix(prefix_path, prefix_content):
    """
    Creates prefix with path to alt-php
    @type prefix_path: str
    @param prefix_path: Path to the prefix file, e.g. /etc/scl/prefix/alt-php70
    @type prefix_content: str
    @param prefix_content: SCL path, e.g. /opt/cloudlinux

    @rtype: bool
    @return: True if file was created sucessfully, False otherwise
    """
    try:
        with open(prefix_path, 'w') as fd:
            fd.write(prefix_content)
    except IOError as e:
        logging.error(u"Couldn't open file %s:\n%s" % (prefix_path, e))
        return False
    return True


def reconfigure(config, int_version):
    """

    @type config:
    @param config:
    @type int_version: str
    @param int_version: Interpreter version (44, 55, 72, etc.)
    @type int_path: str
    @param int_path: Interpreter directory on the disk (/opt/alt/php51, etc.)

    @rtype: bool
    @return: True if reconfiguration was successful, False otherwise
    """
    cp_version = get_cpanel_version()
    prefix_name = "alt-php%s" % int_version
    prefix_path = os.path.join(SCL_PREFIX_PATH, prefix_name)
    prefix_content = "/opt/cloudlinux\n"
    alt_php_enable_file = "/opt/cloudlinux/alt-php%s/enable" % int_version

    if cp_version and rpm.labelCompare(
            ('1', cp_version, '0'), ('1', MIN_CPANEL_VERSION, '0')) < 0:
        status = delete_prefix(prefix_path)

    else:
        try:
            int_enabled = config.getboolean("MultiPHP Manager", prefix_name)
        except configparser.NoOptionError as e:
            int_enabled = True
            logging.warning("Prefix %s doesn't exist in %s:\n" % (prefix_name,
                                                                  CONFIG_PATH))
            config.set("MultiPHP Manager", prefix_name, "yes")
            with open(CONFIG_PATH, 'w') as configfile:
                config.write(configfile)
        except configparser.NoSectionError as e:
            int_enabled = True
            config.add_section('MultiPHP Manager')
            config.set("MultiPHP Manager", prefix_name, "yes")
            with open(CONFIG_PATH, 'w') as configfile:
                config.write(configfile)
            print("Config %s is broken:\nCreated it.\n" % (CONFIG_PATH))

        if int_enabled and os.path.exists(alt_php_enable_file):
            status = create_prefix(prefix_path, prefix_content)
        elif not int_enabled and os.path.exists(prefix_path):
            status = delete_prefix(prefix_path)
        else:
            return True
    return status



def check_alt_path_exists(int_path, int_name, int_ver):
    """
    Check if alt-php path exist
    ----------
    @type int_path:  str or