#!/usr/bin/perl
# cpanel - autofixer2/ea4_address_mod_http2_conflict_with_mod_mpm_prefork
#                                                    Copyright 2017 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::ea4_address_mod_http2_conflict_with_mod_mpm_prefork;

use strict;
use warnings;

if ( $ENV{'CPANEL_BASE_INSTALL'} ) {

    # Don't run on new installs
    exit;
}

exit( keep_one_remove_one( "ea-apache24-mod_mpm_prefork", "ea-apache24-mod_http2" ) ) if !caller();

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

# TODO/YAGNI: make this re-useable if we get more of these types of autofixers

sub keep_one_remove_one {
    my ( $keep, $remove ) = @_;

    # exit() value
    return 0 if !eval "require Cpanel::PackMan;1";    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)

    my $pkm = Cpanel::PackMan->instance();

    if ( $pkm->is_installed($remove) && $pkm->is_installed($keep) ) {
        print "Removing $remove since it now conflicts w/ $keep …\n";

        eval { $pkm->sys->uninstall($remove) };
        my $err = $@;
        if ( !$err ) {                                # uninstall() bug noted in ZC-2763
            if ( $pkm->is_installed($remove) ) {
                $err = "Unknown Error";
            }
        }

        if ($err) {
            print "\t!!!! failed to remove $remove this will need done manually (or remove $keep) !!\n";
            print "\t\tError: $err\n";
            _send( $keep, $remove, $err );
            print " … done!\n";
            return 1;                                 # exit() value
        }
        else {
            _send( $keep, $remove, 0 );
            print " … done!\n";
        }
    }

    return 0;                                         # exit() value
}

sub _send {
    my ( $keep, $remove, $failed_to_remove ) = @_;

    if ( eval "require Cpanel::iContact::Class::EasyApache::EA4_ConflictRemove;1" ) {    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        print "\tSending iContact (EA4_ConflictRemove)\n";

        # yes, new() actually results in message delivery <facepalm>
        Cpanel::iContact::Class::EasyApache::EA4_ConflictRemove->new(
            tried_to_keep    => $keep,
            tried_to_remove  => $remove,
            failed_to_remove => $failed_to_remove,
        );
    }
    else {
        print "\tiContact N/A: System does not have the iContact module “EA4_ConflictRemove\n";
    }

    return;
}
