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

import os

import php_merge
import php_layout

class CgiPhpSanityCheck:
    __options = None
    __accepted_options = ["type", "remove", "override", "virtual_host", "global_config", "config_path", "cgi_bin"]

    def __init__(self, options):
        self.__options = options

    def check(self):
        if not getattr(self.__options, 'type', None) or self.__options.type != "cgi":
            raise Exception("Internal Error: Wrong php service type(%s) for php cgi" % self.__options.type)

        for key in vars(self.__options):
            attr = getattr(self.__options, key, None)
            if attr and key not in self.__accepted_options:
                    raise Exception("The option '%s' is not acceptable for php cgi" % key)

        if not getattr(self.__options, 'config_path', None) and not getattr(self.__options, 'virtual_host', None):
            raise Exception("Please specify either '--virtual-host' option or path to vhost's config")

class CgiPhpIniConfig:
    config = None
    server_wide_php_ini = None
    vhost = None

    """ Custom php.ini for fastcgi/cgi PHP handers configuration class.
        sysuser and pool_dir options are not using here, but added to unify declaration with fpm.
    """
    def __init__(self, options):
        self.vhost = options.virtual_host
        self.server_wide_php_ini = options.global_config if options.global_config else php_layout.SERVER_WIDE_PHP_INI

    def merge(self, override_file=None, has_input_stream=True):
        self.config = php_merge.merge_input_configs(self.server_wide_php_ini, override_file, has_input_stream=has_input_stream)

    def infer_config_path(self):
        vhosts_system_d = php_layout.get_vhosts_system_d()
        return os.path.join(vhosts_system_d, self.vhost, 'etc', 'php.ini')

    def open(self, config_path):
        parent_dir = os.path.dirname(config_path)
        if not os.path.exists(parent_dir):
            os.mkdir(parent_dir)
            os.chown(parent_dir, 0, 0)

        return open(config_path, 'wb')

    def write(self, fileobject):
        fileobject.write(php_layout.AUTOGENERATED_CONFIGS)
        fileobject.write('\n')
        self.config.writefp(fileobject)

    def check(self):
        return True

DECLARES = {
    "init": CgiPhpSanityCheck,
    "config": CgiPhpIniConfig,
    "service": None
}
