#!/usr/bin/python

import os
import sys
import getopt
import re
import pwd
import csv
import simplejson
import tempfile
import base64
from stat import S_IRUSR, S_IWUSR, S_IRGRP, S_IROTH
import subprocess
import signal


class IniHandler(object):
    USER_INI_FILENAME = 'alt_php.ini'
    """
    Gets and sets CloudLinux
    PHP-selector PHP.ini settings
    """
    def __init__(self, username=None, config=None,
                 version=None, outputFormat='text'):
        """
        Initializes class with username,
        config file and version
        """
        self.format = outputFormat
        self.userIniConfig = 'alt_php.ini'
        self.lastMessageStatus = None
        self.messageWeight = {
            'ERROR':3,
            'WARN':2,
            'OK':1
        }
        if not username:
            self.printData({
                'status':'ERROR',
                'message':'No username supplied'
            })
            sys.exit(1)

        self.username = username
        self.uid = self.getUserID()
        self.selectorConfig = self.getSelectorConfig()

        # php.ini selector configuration file
        if not config:
            self.iniConfigPath = '/etc/cl.selector/php.conf'
        else:
            self.iniConfigPath = config

        if not os.path.isfile(self.iniConfigPath):
            self.printData({
                'status':'ERROR',
                'message':"config file %s does not exists" %
                    (self.iniConfigPath,)
            })
            sys.exit(2)

        # If version is not supplied get a user's current one
        if version:
            if version == 'native':
                self.printData({
                   'status':'ERROR',
                   'message':'You cannot change settings for native version'
                })
                sys.exit(1)
            patt = re.compile(r'\d+\.\d+')
            if patt.match(version):
                if version in self.selectorConfig:
                    self.version = version
                else:
                    self.printData({
                        'status':'ERROR',
                        'message':'Version %s does not exist' % (version,)
                    })
                    sys.exit(1)
        else:
            self.version = self.getSelectorVersion()

    def getDefaultSelectorVersion(self):
        """
        Returns system default PHP version from
        /etc/cl.selector/defaults.cfg file
        """
        default_config = '/etc/cl.selector/defaults.cfg'
        if not os.path.isfile(default_config):
            return 'native' # in the absence of file all should be by default
        cfg = open( default_config, 'r' )
        is_found = False
        for line in cfg:
            if line.startswith( '[versions]' ):
                is_found = True
                continue
            if is_found and '=' in line:
                version = line[line.find('=')+1:].strip()
                break
        cfg.close()
        return version

    def getUserID(self):
        """
        Returns last two digits of a user uid as a string
        """
        try:
            uid = pwd.getpwnam(self.username).pw_uid
        except KeyError:
            self.printData({
                'status':'ERROR',
                'message':"user %s does not exist" % (self.username,)
            })
            sys.exit(1)
        except:
            self.printData({
                'status':'ERROR',
                'message':'Cannot get user ID'
            })
            sys.exit(1)
        return str(uid)[-2:]

    def getSelectorConfig(self):
        """
        If version is provided returns dictionary
        of settings for a specified version. If not,
        returns dictionary for all versions
        """
        config_path = '/etc/cl.selector/selector.conf'
        data = {}
        if not os.path.isfile:
            self.printData({
                'status':'ERROR',
                'message':'no selector configuration file'
            })
            sys.exit(1)

        cf = open(config_path, 'r')
        for line in cf:
            parts = line.split()
            key = parts[1].strip()  # we use short version (e.g 5.3) as key for dict
            if not key in data:
                data[ key ] = {}
            # full version, e.g. 5.3.12
            data[ key ]['version'] = parts[2].strip()
            # item (e.g. php-cli) mapped to path
            data[key][parts[0].strip()] = parts[3].strip()
        cf.close()
        return data

    def getSelectorVersion(self):
        """
        If no php-selector version supplied
        find it out by tracing links of alternative
        php binaries
        """
        selector_dir = os.path.join(
            '/var/cagefs',
            self.uid,
            self.username,
            'etc',
            'cl.selector'
        )
        if not os.path.isdir(selector_dir):
            self.printData({
                'status':'ERROR',
                'message':'No user selector directory'
            })
            sys.exit(2)
        for item in os.listdir(selector_dir):
            file = os.path.join(selector_dir, item)
            if not os.path.islink(file):
                continue
            path = os.readlink(file)
            if item == 'php' and os.path.dirname(path) == '/usr/selector':
                # currently we do not want to handle native version
                self.printData({
                    'status':'ERROR',
                    'message':'You cannot change ini settings for native version'
                })
                sys.exit(1)
            for version in self.selectorConfig.keys():
                if ('php' in self.selectorConfig[version] and
                        self.selectorConfig[version]['php'] == path):
                    return version
        self.printData({
            'status':'ERROR',
            'message':'Cannot reliably get current php selector version'
        })
        sys.exit(1)

    def getUserIniPath(self):
        """
        Returns path to alternative user
        php.ini file (alt_php.ini)
        """
        base_path = os.path.join(
            '/var/cagefs',
            self.uid,
            self.username,
            'etc',
            'cl.php.d'
        )
        if not os.path.isdir(base_path):
            self.printData({
                'status':'ERROR',
                'message':"No ini directory for user %s" % (self.username,)
            })
            sys.exit(1)
        return os.path.join(
            base_path,
            'alt-php%s' % (''.join(self.version.split('.')),)
        )

    def checkVersion(self, test):
        """
        Compares version in use and version required by PHP feature
        and return true if PHP feature satisfies
        """
        if self.version not in self.selectorConfig:
            self.printData({
                'status':'ERROR',
                'message':"No data in config for version %s" % (self.version,)
            })
            sys.exit(1)
        v_array = map(
            (lambda x: int(x) ),
            self.selectorConfig[self.version]['version'].split('.')
        )
        patt = re.compile(r'([<>=]{1,2})?(\d+\.\d+\.\d+)\.?')
        m = patt.match(test)
        if not m:
            self.printData({
                'status':'ERROR',
                'message':"Cannot compare to supplied value: %s" % (test,)
            })
            sys.exit(1)
        action = m.group(1)
        test = map(
            (lambda x: int(x)),
            m.group(2).split('.')
        )
        version_int = v_array[0] << 11 | v_array[1] << 7 | v_array[2]
        test_int = test[0] << 11 | test[1] << 7 | test[2]
        if action == r'<' and version_int < test_int:
            return True
        if action == r'>=' and version_int >= test_int:
            return True
        if ( not action or action == '=' ) and version_int == test_int:
            return True
        return False

    def getIniConfig(self):
        """
        Parses php config file (not php.ini!) and returns a structure
        """
        self.config = {}
        deletes = set()
        config_file = open( self.iniConfigPath, 'r' )
        for line in config_file:
            if '=' not in line:
                continue;
            if line.startswith('Directive'):
                divider = line.find('=')
                if divider > 0:
                    directive = line[ divider+1 : ].strip()
                    self.config[directive] = {}
            else:
                items = line.split('=', 1)
                key = items[0].strip().lower()
                if key in self.config[directive]:
                    continue;
                value = items[1].strip()
                if key == 'remark':
                    if not self.checkVersion(value):
                        deletes.add(directive)
                else:
                    self.config[directive][key] = value
        config_file.close()
        for i in deletes:
            self.config.pop( i, None )
        self.getIniDefaults()
        if self.username:
            self.getUserIni()

    def getUserIni(self):
        """
        Parses user ini file and updates
        values of existing data
        """
        ini_path = self.getUserIniPath()
        filename = 'alt_php.ini'
        ini_file = os.path.join(ini_path, filename)
        if os.path.isfile(ini_file):
            ini = open(ini_file, 'r')
            for line in ini:
                if line.startswith(';'):
                    continue
                if '=' in line:
                    pair = line.split('=')
                    key = pair[0].strip()
                    if key in self.config:
                        self.config[key]['value'] = pair[1].strip()
            ini.close()

    def getIniDefaults(self):
        """
        Gets PHP defaults (calls php -i)
        """
        if not 'php' in self.selectorConfig[self.version]:
            self.printData({
                'status':'ERROR',
                'message':"No data in config for version %s" % (self.version,)
            })
            sys.exit(1)
        if not os.path.isfile( self.selectorConfig[self.version]['php'] ):
            self.printData({
                'status':'ERROR',
                'message':"No binary for version %s" % (self.version,)
            })
            sys.exit(2)
        env_data = os.environ
        if ('SCRIPT_FILENAME' in env_data):
            script_path = '/usr/share/l.v.e-manager/commons/misc/clinfo.php'
            if os.path.exists(script_path):
                env_data['SCRIPT_FILENAME'] = script_path
            process_params = [ self.selectorConfig[self.version]['php'] ]
        else:
            process_params = [
                self.selectorConfig[self.version]['php'],
                '-qi'
            ]
        env_data['PHP_FCGI_MAX_REQUESTS'] = '1'
        env_data['PHP_FCGI_CHILDREN'] = '0'
        phpinfo = subprocess.Popen(
            process_params,
            stdin=open('/dev/null'),
            stderr=subprocess.STDOUT,
            stdout=subprocess.PIPE,
            close_fds=True,
            env=env_data,
        )
        tag_pattern = re.compile(
            r'<tr[^>]*?><td[^>]*>(.*?)</td><td[^>]*>(.*?)</td>(?:<td[^>]*>(.*?)</td>)?</tr>')
        strip_pattern = re.compile(r'<[^>]*?>')
        lines = tag_pattern.findall(phpinfo.communicate()[0])
        for l in lines:
            directive = re.sub(strip_pattern, '', l[0])
            value = re.sub(strip_pattern, '', (l[2] or l[1]))
            if directive in self.config:
                if value == 'no value':
                    if ('default' in self.config[directive] and
                            self.config[directive]['default'] != ""):
                        continue
                    else:
                        self.config[directive]['default'] = ""
                else:
                    if directive == 'error_reporting':
                        value = self.getErrorDesc(value)
                    self.config[directive]['default'] = value

    def getErrorDesc(self, value):
        if not re.match( r'^\d+$', value):
            return ''
        if value == '32767' and self.checkVersion('>=5.4.0'):
            return 'E_ALL'
        elif value == '30719' and self.checkVersion('>=5.3.0'):
            return 'E_ALL'
        elif value == '6143' and self.checkVersion('>=5.2.0'):
            return 'E_ALL'
        elif value == '2047' and self.checkVersion('<5.2.0'):
            return 'E_ALL'
        else:
            php_error = {
                1    :'E_ERROR',
                2    :'E_WARNING',
                4    :'E_PARSE',
                8    :'E_NOTICE',
                16   :'E_CORE_ERROR',
                32   :'E_CORE_WARNING',
                64   :'E_COMPILE_ERROR',
                128  :'E_COMPILE_WARNING',
                256  :'E_USER_ERROR',
                512  :'E_USER_WARNING',
                1024 :'E_USER_NOTICE',
                2048 :'E_STRICT',
                4096 :'E_RECOVERABLE_ERROR',
                8192 :'E_DEPRECATED',
                16384:'E_USER_DEPRECATED',
                32767:'E_ALL'
            }
        desc = []
        value = int(value)
        for error in php_error:
            if (error & value) == error:
                desc.append(php_error[error])
            return r' | '.join(desc)

    def printData(self, data=None):
        """
        Just a wrapper around class printing subroutines
        """
        if data:
            if (self.lastMessageStatus and
                    self.lastMessageStatus >=
                    self.messageWeight[ data['status'] ]):
                return
            self.lastMessageStatus = self.messageWeight[ data['status'] ]
        dispatcher = {
            'json':self.printJSON,
            'perl':self.printPerl,
            'csv' :self.printCSV,
            'text':self.printText
        }
        dispatcher[self.format](data)

    def printJSON(self, data=None):
        """
        Prints data in JSON format
        (for AJAX calls)
        """
        if data:
            print simplejson.dumps(data)
        else:
            self.getIniConfig()
            print simplejson.dumps({'status':'OK', 'data':self.config})

    def printText(self, data=None):
        """
        Prints data in pure text
        """
        if data:
            print "%s:%s" % ( data['status'], data['message'] )
        else:
            self.getIniConfig()
            for opt in sorted(self.config.keys()):
                print "TITLE:%s" % (opt,)
                for key in self.config[opt].keys():
                    print '%s:%s' % (key.upper(), self.config[opt][key])
                print ''

    def printPerl(self, data=None):
        """
        Prints data as Perl anonymous array of hashes
        (to form Cpanel templates data)
        """
        if data:
            print ("{status=>%s, message=>%s}" %
                (data['status'], data['message']))
        else:
            self.getIniConfig()
            data = []
            for opt in sorted(self.config.keys()):
                structure = []
                structure.append('title=>"%s"' % (opt,))
                for key in self.config[opt].keys():
                    structure.append(
                        '%s=>"%s"' % (key, self.config[opt][key]))
                data.append("{%s}" % (','.join(structure)))
            print '[%s]' % (','.join(data),)

    def printCSV(self, data=None):
        """
        Prints data as comma separated values
        """
        csv_out = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
        if data:
            csv_out.writerow(
                ['status', data['status'], 'message', data['message']])
        else:
            self.getIniConfig()
            for opt in sorted(self.config.keys()):
                flat_array = [opt]
                for key, value in self.config[opt].iteritems():
                    flat_array.extend([key, value])
                csv_out.writerow(flat_array)

    def handle_option_item(self, option_item, expect_separator=True):
        if ':' in option_item:
            option_name, option_value = option_item.split(':', 1)
        else:
            if not expect_separator:
                option_name, option_value = option_item, ''
            else:
                self.printData({
                    'status':'ERROR',
                    'message':"Colon as a separator expected (%s)!" % (option_item,)
                })
                sys.exit(1)
        return {option_name: option_value}


    def get_ini_data_parsed(self, parse_options=True):
        '''
        Parses ini file and returns dictionary of processed ini options and
        and list of other content that should be simply preserved.
        '''
        ini_options = {}
        other_content = []
        ini_path = self.getUserIniPath()
        ini_file = os.path.join(ini_path, IniHandler.USER_INI_FILENAME)

        if os.path.isfile(ini_file):
            ini = open(ini_file, 'r')
            inside = False
            for line in ini:
                if line.startswith(';>==='):
                    inside = True
                    continue
                if line.startswith(';<==='):
                    inside = False
                    continue
                if inside:
                    if not parse_options:
                        continue
                    if '=' not in line:
                        continue
                    ini_options.update(
                        dict([map((lambda x:x.strip()), line.split('=', 1))]))
                else:
                    other_content.append(line.rstrip())
            ini.close()
        return ini_options, other_content

    def remove_forbidden_options_or_exit(self, options, quiet=True):
        '''
        Check if all options to process are present in white list
        and removes forbidden ones or exits with error
        '''
        if not set(options.keys()).issubset(set(self.config.keys())):
            white_list_options = {}
            for opt_name, opt_value in options.iteritems():
                if opt_name not in self.config:
                    if quiet:
                        continue
                    else:
                        self.printData({
                            'status':'ERROR',
                            'message':"No '%s' option in white list!" % (opt_name,)
                        })
                        sys.exit(1)
                white_list_options[opt_name] = opt_value
            options = white_list_options
        return options

    def compose_options_set(self, options):
        options_set = []
        for opt_name, opt_value in options.items():
            options_set.append("%s=%s" % (opt_name, opt_value))
        return options_set

    def process_option_string(self, optset, decoder, expect_separator=True):
        options = {}
        if optset:
            for option_item in optset.split(','):
                option_item = decoder(option_item)
                options.update(
                    self.handle_option_item(
                        option_item, expect_separator))
        return options

    def insertUserOptions(self, optset, decoder, append=False, quiet=False):
        """
        Inserts supplied options into current ones
        """
        self.getIniConfig()

        options = self.process_option_string(
            optset=optset, decoder=decoder, expect_separator=True)

        options = self.remove_forbidden_options_or_exit(options, quiet)

        ini_options, other_content = self.get_ini_data_parsed(append)

        # merge current options dictionary and supplied options dictionary
        if append:
            ini_options.update(options)
            options_set = self.compose_options_set(ini_options)
        else:
            options_set = self.compose_options_set(options)
        self.processOptionSet(options_set, other_content)
        self.json_print_ok()

    def deleteUserOptions(self, optset, decoder, quiet=False):
        """
        Deletes supplied options from current ones
        """
        self.getIniConfig()

        options = self.process_option_string(
            optset=optset, decoder=decoder, expect_separator=False)

        ini_options, other_content = self.get_ini_data_parsed(parse_options=True)

        # exclude supplied options from current dictionary
        options_set = []
        for opt_name, opt_value in ini_options.iteritems():
            if opt_name in options:
                continue
            options_set.append('%s=%s' % (opt_name, opt_value))
        self.processOptionSet(options_set, other_content)
        self.json_print_ok()

    def json_print_ok(self):
        if self.format == 'json':
            self.printData({
                'status':'OK',
            })

    def processOptionSet(self, options_set, other_content):
        """
        Prepares data for actual saving to a file
        """
        data_to_write = []
        if len(options_set) != 0:
            data_to_write.insert(0,
                ';>=== Start of PHP Selector Custom Options ===')
            data_to_write.extend(options_set)
            data_to_write.append(
                ';<=== End of PHP Selector Custom Options =====')
        backup_data = '\n'.join(data_to_write)+'\n'
        data_to_write.extend(other_content)
        self.writeData(self.getUserIniPath(), IniHandler.USER_INI_FILENAME,
            '\n'.join(data_to_write)+'\n')
        self.doBackup(backup_data)
        self.reloadProcesses()

    def reloadProcesses(self):
        """
        Reload a user processes after making changes in configuration
        """
        ps = subprocess.Popen(
            [
                '/bin/ps',
                '-U', self.username,
                '-u', self.username
            ],
            stdout=subprocess.PIPE
        )
        lines = ps.communicate()[0].split("\n")
        for row in lines:
            parts = row.rstrip().split()
            try:
                parts[-1].index('php')
                os.kill(int(parts[0]), signal.SIGHUP)
            except IndexError:
                continue
            except ValueError:
                continue

    def doBackup(self, data):
        """
        On saving user settings keep backup on user homedir
        """
        if not self.username:
            return
        user_home = pwd.getpwnam(self.username).pw_dir
        backup_dir = os.path.join(user_home, '.cl.selector')
        if not os.path.isdir(backup_dir):
            return
        backup_file = 'alt_php' + ''.join(self.version.split('.')) + '.cfg'
        backup_path = os.path.join(backup_dir, backup_file)
        self.writeData(backup_dir, backup_file, data)

    def writeData(self, filepath, filename, data):
        """
        Saves data to a file
        """
        obj_uid = pwd.getpwnam(self.username).pw_uid
        obj_gid = pwd.getpwnam(self.username).pw_gid
        euid_is_changed = False
        subj_euid = os.geteuid()
        subj_egid = os.getegid()
        if subj_euid != obj_uid:
            try:
                os.setegid(obj_gid)
                os.seteuid(obj_uid)
                euid_is_changed = True
            except OSError:
                self.printData({
                    'status':'ERROR',
                    'message':"Failed to change to %s EUID" % (self.username,)
                })
                sys.exit(1)
        try:
            full_path = '/'.join( [ filepath, filename ] )
            fd, temp_path = tempfile.mkstemp( prefix='lvetmp_', dir=filepath )
            fo = os.fdopen(fd, 'w')
            fo.write(data)
            fo.close()
        except (IOError, OSError):
            try:
                if os.path.exists(temp_path):
                    os.unlink(temp_path)
            except:
                pass
        else:
            try:
                mask = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
                os.rename(temp_path, full_path)
                os.chmod(full_path, mask)
            except OSError:
                pass
        if euid_is_changed:
            os.setegid(subj_egid)
            os.seteuid(subj_euid)

def usage():
    print ''
    print 'Usage: ' + sys.argv[0] + ' [OPTIONS]'
    print 'Options:'
    print ''
    print ' -r | --replace   : replaces user php.ini options with supplied comma-separated'
    print '                    list of colon-separated key:value pairs'
    print ' -a | --append    : appends supplied comma-separated list of colon-separated'
    print '                    key:value pairs to user php.ini options'
    print ' -d | --delete    : deletes supplied comma-separated list of option names'
    print '                    from user php.ini options'
    print ' -B | --base64    : expects data as comma-separated base64-encoded string'
    print ' -j | --json      : return data as JSON'
    print ' -V | --csv       : return data as comma separated values'
    print ' -p | --perl      : return data as perl "hash"'
    print ' -u | --user      : specify the user'
    print ' -v | --version   : specify php version'
    print ' -q | --quiet     : suppress errors messages for wrong input'
    print ' -h | --help      : print this message'
    print 'By default basic set of options is outputted as text'
    print ''


def check_mutually_exclusive(list_to_check_against, options_set):
    '''
    Checks mutually exclusive command line options and exits if found
    '''
    # we expect to find no more than one item from 'list_to_check_against'
    # in options keys list. If more than one -- exit with error
    intersect = set(list_to_check_against).intersection(
        set(options_set.keys()))
    if len(intersect) > 1:
        message_fmt_string = 'ERROR: ' + ' '.join(
            ['"%s"']*len(intersect)) + ' are mutually exclusive'
        print message_fmt_string % tuple(intersect)
        sys.exit(1)

def dumb_string_returner(data):
    return data

def main():

    config = {}
    config['format']  = 'text'
    config['version'] = None
    config['config']  = None
    config['user']    = None
    config['quiet']   = False
    config['base64']  = False

    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'qhjpVBu:v:c:r:d:a:',
            ['quiet', 'base64', 'help', 'json', 'perl', 'csv', 'user=',
                'version=', 'config=', 'replace=', 'append=', 'delete=']
        )
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in [ '-h', '--help' ]:
            usage()
            sys.exit(0)
        elif o in [ '-j', '--json' ]:
            config['format'] = 'json'
        elif o in [ '-p', '--perl' ]:
            config['format'] = 'perl'
        elif o in [ '-V',  '--csv' ]:
            config['format'] = 'csv'
        elif o in [ '-u', '--user' ]:
            config['user'] = a
        elif o in [ '-v', '--version' ]:
            config['version'] = a
        elif o in [ '-c', '--config' ]:
            config['config'] = a
        elif o in [ '-r', '--replace' ]:
            config['replace'] = a
        elif o in [ '-d', '--delete' ]:
            config['delete'] = a
        elif o in [ '-a', '--append' ]:
            config['append'] = a
        elif o in [ '-q', '--quiet' ]:
            config['quiet'] = True
        elif o in [ '-B', '--base64' ]:
            config['base64'] = True

    data = IniHandler(
        config['user'], config['config'], config['version'], config['format'])

    # 'replace', 'append', 'delete' are mutually exclusive. Let's check it
    check_mutually_exclusive(['replace', 'append', 'delete'], config)

    decoder = dumb_string_returner
    if config['base64']:
        decoder = base64.b64decode

    if 'replace' in config:
        data.insertUserOptions(optset=config['replace'], decoder=decoder,
            quiet=config['quiet'], append=False)
    elif 'append' in config:
        data.insertUserOptions(optset=config['append'], decoder=decoder,
            quiet=config['quiet'], append=True)
    elif 'delete' in config:
        data.deleteUserOptions(
            optset=config['delete'], decoder=decoder, quiet=config['quiet'])
    else:
        data.printData()


if __name__ == '__main__':
    main()
