#!/usr/local/cpanel/3rdparty/bin/perl

# cpanel - etc/ea4/999-php_ini                     Copyright 2023 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
use cPstrict;

use Whostmgr::API::1::Lang::PHP ();
use Cpanel::ProgLang;    # oooold versions do not have this so require it after the version check

my $php            = Cpanel::ProgLang->new( type => 'php' );
my $installed_phps = $php->get_installed_packages();           # this always returns an array ref
for my $php_version ( @{$installed_phps} ) {                   # ea-php74
    my $ini_settings = Whostmgr::API::1::Lang::PHP::php_ini_get_directives( { version => $php_version } );
    next unless ref $ini_settings->{'directives'} eq 'ARRAY';

    # 'directive name' => 'default value we want to use'
    my $settings_to_fix = {
        'memory_limit'        => 128,
        'upload_max_filesize' => 32,
        'post_max_size'       => 32,
    };

    foreach my $setting ( $ini_settings->{'directives'}->@* ) {
        my $directive = $setting->{'key'};
        next unless exists $settings_to_fix->{$directive};

        my $current_limit = $setting->{'value'};
        next unless $current_limit =~ m/^\s*(\d+)M\s*$/a;    # look for a pattern like 32M. If we don't see it, pass on messing with it. root must have explicitly set this.
        $current_limit = $1;
        next if $current_limit >= $settings_to_fix->{$directive};

        say "Updating '$directive' in php.ini to $settings_to_fix->{$directive}M for $php_version";
        my $metadata = {};
        Whostmgr::API::1::Lang::PHP::php_ini_set_directives( { version => $php_version, directive => "$directive:$settings_to_fix->{$directive}M" }, $metadata );
    }
}
