{

use esmith::AccountsDB;
use esmith::php;
my $a = esmith::AccountsDB->open_ro || die "Couldn't open the accounts database";

foreach my $ibay ($a->get_all_by_prop(type => 'ibay')){
  my $version		  = PhpFpmVersionToUse($ibay); 
  my $dynamic             = $ibay->prop('CgiBin') || 'disabled';
  my $custom              = $ibay->prop('CustomPool') || undef;
  next unless ($dynamic eq 'enabled' && $version eq $PHP_VERSION && !$custom);
  my $key                 = $ibay->key;
  my $name                = lc $key;
  my $pool_name           = 'php' . $version . '-' . $name;
  my $memory_limit        = $ibay->prop('MemoryLimit')       || $defaultPHPproperties{'MemoryLimit'};
  my $max_execution_time  = (defined $ibay->prop('MaxExecutionTime') ) ? $ibay->prop('MaxExecutionTime') : $defaultPHPproperties{'MaxExecutionTime'};
  my $max_input_time      = (defined $ibay->prop('MaxInputTime'))? $ibay->prop('MaxInputTime') : $defaultPHPproperties{'MaxInputTime'};
  my $allow_url_fopen     = $ibay->prop('AllowUrlFopen')     || $defaultPHPproperties{'AllowUrlFopen'};
  my $post_max_size       = $ibay->prop('PostMaxSize')       || $defaultPHPproperties{'PostMaxSize'};
  my $upload_max_filesize = $ibay->prop('UploadMaxFilesize') || $defaultPHPproperties{'UploadMaxFilesize'};
  my $file_upload         = $ibay->prop('FileUpload')        || $defaultPHPproperties{'FileUpload'};
  my $display_errors	  = $ibay->prop('DisplayErrors') || 'off'; #we do not set this one at php level to avoid to have a whole server displaying errors and security issues
  my $error_reporting	  = $ibay->prop('ErrorReporting') || 'E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT'; #same reason, we hardcoded the default
  my $open_basedir        = $ibay->prop('PHPBaseDir')           || '/home/e-smith/files/ibays/' . $key . '/' . ':/var/lib/php/' . $key . '/';

  my $disabled_functions  = (defined $ibay->prop('DisabledFunctions')) ? $ibay->prop('DisabledFunctions') :  $defaultPHPproperties{'DisabledFunctions'};
  my $autoprepend         = $ibay->prop('AutoPrependFile')  || $defaultPHPproperties{'AutoPrependFile'};
  my $MailForceSender	  = $ibay->prop('MailForceSender')  || "$name\@$DomainName"; # TODO => check ibay associated domains.
  my $limitExtensions     = ( ($ibay->prop('AllowPHTML') || $defaultPHPproperties{'AllowPHTML'} ) eq 'enabled' ) ? "security.limit_extensions= .php .htm .html .phar .phtml .xml " : "";

  # Format vars 
  my $autoprep            = ( $autoprepend eq "disabled") ? "" : "/usr/share/php/auth_translation.php";
  my $autoprepath         = ( -d  "/opt/remi/php$version/root/usr/share/pear/" && -d "/opt/remi/php$version/root/usr/share/php/" ) ? ":/usr/share/php/:/usr/share/pear/:/opt/remi/php$version/root/usr/share/pear/:/opt/remi/php$version/root/usr/share/php/" : ":/usr/share/php/:/usr/share/pear/";
  $file_upload        = ($file_upload =~ m/^1|yes|on|enabled$/) ?     'on' : 'off';
  $allow_url_fopen    = ($allow_url_fopen =~ m/^1|yes|on|enabled$/) ? 'on' : 'off';
  $disabled_functions = join(', ', split /[,;:]/, $disabled_functions);
  $display_errors     = ($display_errors  =~ m/^1|yes|on|enabled$/) ? 'on' : 'off';
  $error_reporting    = ($error_reporting eq 'E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT') ? '; default error_reporting' : "php_value[error_reporting] = $error_reporting";
  $open_basedir       = join(':',  split(/[,;:]/, $open_basedir .  $autoprepath));
  my $max_input_vars      = (defined $ibay->prop('MaxInputVars'))? $ibay->prop('MaxInputVars') : $defaultPHPproperties{'MaxInputVars'} || '1000';
  my $short_open_tag      = (defined $ibay->prop('ShortOpenTag'))? $ibay->prop('ShortOpenTag') : $defaultPHPproperties{'ShortOpenTag'} || 'On';
  my $sessionProb         = (defined $ibay->prop('SessionProbability'))? $ibay->prop('SessionProbability') : $defaultPHPproperties{'SessionProbability'} || '1';
  my $max_children        = (defined $ibay->prop('PHPmaxChildren'))? $ibay->prop('PHPmaxChildren') : $defaultPHPproperties{'PHPmaxChildren'} || 20;
  my $min_spare_servers   = (defined $ibay->prop('PHPminServers'))? $ibay->prop('PHPminServers') : $defaultPHPproperties{'PHPminServers'} || 4;
  my $start_servers       = (defined $ibay->prop('PHPstartServers'))? $ibay->prop('PHPstartServers') : $defaultPHPproperties{'PHPstartServers'} || 6;
  my $max_spare_servers   = (defined $ibay->prop('PHPmaxServers'))? $ibay->prop('PHPmaxServers') : $defaultPHPproperties{'PHPmaxServers'} || 8;
  my $max_requests        = (defined $ibay->prop('PHPmaxRequests'))? $ibay->prop('PHPmaxRequests') : $defaultPHPproperties{'PHPmaxRequests'} || 1000;
  $min_spare_servers      = ( $min_spare_servers > $max_spare_servers ) ? sprintf("%.0f", $max_spare_servers/2) : $min_spare_servers;
  $start_servers          = ( $start_servers > $max_spare_servers ) ? sprintf("%.0f", $max_spare_servers/2 +  $min_spare_servers/2  ) : $start_servers;

### APCu
    my $apcu_so = "/opt/remi/php${PHP_VERSION}/root/usr/lib64/php/modules/apcu.so";
    my $apc = "; APCu disabled for $pool_name";
    # Check if APCu is enabled via ibay property or global default (defaults to disabled unless set)

    if (-f $apcu_so ) {
    my $apcEnabled = (defined $ibay->prop('apcEnabled'))
        ? $ibay->prop('apcEnabled')
        : ($defaultPHPproperties{'apcEnabled'} || 'disabled');

    # Only output settings if the Remi module is installed AND enabled in SME DB
    if (-f $apcu_so && $apcEnabled eq 'enabled') {
        my $apcTtl = (defined $ibay->prop('apcTtl'))
            ? $ibay->prop('apcTtl')
            : ($defaultPHPproperties{'apcTtl'} || '7200');

        $apc .= "php_admin_flag[apc.enabled] = on\n";
        $apc .= "php_admin_value[apc.ttl] = $apcTtl\n";
        }
        else {
            $apc .= "php_admin_flag[apc.enabled] = off\n";
    }
  }

###OPcache
    my $opcache_so  = "/opt/remi/php${PHP_VERSION}/root/usr/lib64/php/modules/opcache.so";
    my ($opcache_ini) = glob("/etc/opt/remi/php${PHP_VERSION}/php.d/*opcache.ini");
    my $opcache = "; opcache disable ";

    # Only configure OPcache directives if the Remi module and its active .ini exist
    if (-f $opcache_so && defined $opcache_ini && -f $opcache_ini) {

        my $opcacheEnabled = (defined $ibay->prop('opcacheEnabled'))
            ? $ibay->prop('opcacheEnabled')
            : ($defaultPHPproperties{'opcacheEnabled'} || 'enabled');

        if ($opcacheEnabled eq 'enabled') {
            my $opcacheRevalFreq = (defined $ibay->prop('opcacheRevalFreq'))
                ? $ibay->prop('opcacheRevalFreq')
                : ($defaultPHPproperties{'opcacheRevalFreq'} || '1');

            my $opcacheSaveComments = (defined $ibay->prop('opcacheSaveComments'))
                ? $ibay->prop('opcacheSaveComments')
                : ($defaultPHPproperties{'opcacheSaveComments'} || '1');

            my $opcacheJit = (defined $ibay->prop('opcacheJit'))
                ? $ibay->prop('opcacheJit')
                : ($defaultPHPproperties{'opcacheJit'} || 'off');

            $opcache .= "php_admin_flag[opcache.enable] = on\n";
            $opcache .= "php_admin_value[opcache.file_cache] =\n";
            $opcache .= "php_admin_value[opcache.enable_cli] = 1\n";
            $opcache .= "php_admin_value[opcache.save_comments] = $opcacheSaveComments\n";
            $opcache .= "php_admin_value[opcache.revalidate_freq] = $opcacheRevalFreq\n";

            # opcache.jit was introduced in PHP 8.0 (PHP_VERSION >= 80)
            if ($PHP_VERSION >= 80) {
                $opcache .= "php_admin_value[opcache.jit] = $opcacheJit\n";
            }
        }
        else {
            # Explicitly disable OPcache for this pool since Remi enables it globally by default
            $opcache .= "php_admin_flag[opcache.enable] = off\n";
            $opcache .= "php_admin_value[opcache.file_cache] =\n";
        }
    }

#### OUTPUT
  $OUT .=<<"_EOF" if ($version eq $PHP_VERSION);

[$pool_name]
user = www
group = www
listen.owner = root
listen.group = www
listen.mode = 0660
listen = /run/php-fpm/$pool_name.sock
pm = dynamic
pm.max_children = $max_children
pm.start_servers = $start_servers
pm.min_spare_servers = $min_spare_servers
pm.max_spare_servers = $max_spare_servers
pm.max_requests = $max_requests
$limitExtensions
slowlog = /var/log/php/$key/slow.log
php_admin_value[session.save_path] = /var/lib/php/$key/session
php_admin_value[opcache.file_cache]  = /var/lib/php/$key/opcache
php_admin_value[upload_tmp_dir] = /var/lib/php/$key/tmp
php_admin_value[sys_temp_dir] = /var/lib/php/$key/tmp
php_admin_value[mail.force_extra_parameters]            = '-f $MailForceSender'
php_flag[display_errors] = $display_errors
$error_reporting
php_admin_flag[log_errors] = on
php_admin_value[error_log] = /var/log/php/$key/error.log
php_admin_value[memory_limit] = $memory_limit
php_admin_value[max_execution_time] = $max_execution_time
php_admin_value[post_max_size] = $post_max_size
php_admin_value[upload_max_filesize] = $upload_max_filesize
php_admin_value[max_input_time] = $max_input_time
php_admin_value[disable_functions] = $disabled_functions
php_admin_flag[allow_url_fopen] = $allow_url_fopen
php_admin_flag[file_uploads] = $file_upload
php_admin_flag[session.cookie_httponly] = on
php_admin_flag[allow_url_include] = off
php_value[session.save_handler] = files
php_admin_value[auto_prepend_file] = $autoprep
php_admin_value[open_basedir] = $open_basedir
php_admin_value[max_input_vars] = $max_input_vars
php_admin_value[short_open_tag] = $short_open_tag
php_admin_value[session.gc_probability] = $sessionProb
$apc
$opcache

_EOF

    # Allow per-ibay custom directives from /etc/e-smith/templates-custom/etc/php-fpm.d/ibays.conf/ibays/$key/*
    $OUT .= esmith::templates::processTemplate(
        {
            MORE_DATA => {
                ibay        => $key,
                PHP_VERSION => $PHP_VERSION,
            },
            TEMPLATE_PATH         => "/etc/php-fpm.d/ibays.conf/ibays/$key",
            TEMPLATE_EXPAND_QUEUE => ['/etc/e-smith/templates-custom'],
            OUTPUT_TYPE           => 'string',
        }
    ) if (-d "/etc/e-smith/templates-custom/etc/php-fpm.d/ibays.conf/ibays"  && -f "/etc/e-smith/templates-custom/etc/php-fpm.d/ibays.conf/ibays/$key" );

}

}
