# Copyright 1999-2017. Plesk International GmbH. All rights reserved.
# vim: ts=4 sts=4 sw=4 et :

import logging as log

import sys

import php_ini
import php_fpm

class PhpIniConfigParser(php_ini.PhpIniConfigParser):
    def is_section_retained(self, section):
        """ Override section retention policy to allow 'php-fpm-pool-settings' as separate section. """
        return (super(PhpIniConfigParser, self).is_section_retained(section) or
                section == php_fpm.PhpFpmPoolConfig.pool_settings_section)

    def remove_pool_settings_section(self):
        """ Removes 'php-fpm-pool-settings' section if present. """
        self.remove_section(php_fpm.PhpFpmPoolConfig.pool_settings_section)

def merge_input_configs(server_wide_filename=None, override_filename=None, allow_pool_settings=False, has_input_stream=True, input_string=False):
    """ Merge all supplied php.ini configuration files and return
        SafeConfigParser object.
        Files are merged in the following order: server-wide, stdin, override.
    """
    config = PhpIniConfigParser()

    if input_string:
        config.readstr(input_string)

    if server_wide_filename:
        try:
            config.read(server_wide_filename)
        except Exception, ex:
            log.debug("Reading server-wide config '%s' failed: %s", server_wide_filename, ex)

    if has_input_stream:
        try:
            config.readfp(sys.stdin)
        except:
            raise RuntimeError("Cannot parse php.ini from stdin: %s" % str(sys.exc_info()[:2]))

    if override_filename:
        try:
            config.read(override_filename)
        except Exception, ex:
            log.debug("Reading override config '%s' failed: %s", override_filename, ex)

    if not allow_pool_settings:
        config.remove_pool_settings_section()

    return config
