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

#                                      Copyright 2025 WebPros International, LLC
#                                                           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'        => "256M",
        'upload_max_filesize' => "32M",
        'post_max_size'       => "32M",
        'max_execution_time'  => 300
    };

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

        my $new_limit = $settings_to_fix->{$directive};
        if ( $new_limit =~ /^\s*(\d+)M\s*$/ ) {
            $new_limit = $1;
        }

        my $current_limit = $setting->{'value'};
        if ( $current_limit =~ m/^\s*(\d+)M\s*$/a ) {
            $current_limit = $1;
        }

        next if $current_limit >= $new_limit;

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