#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - resolve_all_php_handlers_being_none       Copyright 2018 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package autofixer2::resolve_all_php_handlers_being_none;

use strict;
use warnings;
use YAML::Syck            ();
use Cpanel::Config::Httpd ();

exit(0) if !Cpanel::Config::Httpd::is_ea4();    # Cpanel::Config::Httpd::EA4::is_ea4() is not available on older boxes
exit(0) if $ENV{CPANEL_BASE_INSTALL};           # Don't run on new installs

exit( run() ) if !caller();

###############
#### helpers ##
###############

sub run {
    if ( _php_handlers_are_all_none() ) {
        print "All PHP handlers are `none`! Resolving …\n";

        print "\t1. Ensuring we have the latest packages in order to pull in any fixes to the issue that resulted in all PHP handlers being set to `none` …\n";
        system("yum update -y ea-*");

        print "\t2. Attempting to re-set PHP handlers …\n";
        system("/etc/yum/universal-hooks/multi_pkgs/posttrans/ea-__WILDCARD__/009-phpconf.pl");

        print "\t3. Restarting Apache …\n";
        system("/scripts/restartsrv_httpd stop");
        system("/scripts/restartsrv_httpd start");

        if ( _php_handlers_are_all_none() ) {
            print "!! PHP handlers are still all `none`!!\nThis probably means there is a problem w/ an EA4 RPM. Once that is fixed run this script manually or configure the PHP handlers via WHM or /usr/local/cpanel/bin/rebuild_phpconf\n";

            return 1;    # exit value
        }
        else {
            print "The PHP handlers have been reset. Please check them to make sure they are what you want them to be.\n";
        }
    }

    return 0;            # exit value
}

sub _php_handlers_are_all_none {
    return 1 if !-e "/etc/cpanel/ea4/php.conf" || -z _;

    my $php_cnt  = 0;
    my $none_cnt = 0;
    my $conf_hr  = YAML::Syck::LoadFile("/etc/cpanel/ea4/php.conf");

    for my $key ( keys %{$conf_hr} ) {
        next if $key !~ m/^ea-php/;
        $php_cnt++;
        if ( !$conf_hr->{$key} || $conf_hr->{$key} eq 'none' ) {
            $none_cnt++;
            delete $conf_hr->{$key};    # have to do this because 009 will see 'none' as valid and leavr it
        }
    }

    if ( $php_cnt == $none_cnt ) {
        YAML::Syck::DumpFile( "/etc/cpanel/ea4/php.conf", $conf_hr );    # to trigger rebuild, see delete() above
        return 1;
    }
    return;
}

1;
