#!/usr/bin/perl
# cpanel - autofixer2/remove_prelink              Copyright(c) 2016 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package RemovePrelink;

use strict;
use warnings;

exit run() unless caller();

sub run {
    return 0 if prelink_is_wanted();
    return 0 unless prelink_is_installed();
    return 0 unless prelink_is_enabled();

    # For more information, see CPANEL-4332.
    print "Prelink is installed and enabled. This can cause cPanel RPMs to break during yum updates.\n";

    remove_prelink();
    undo_prelink_damage();
    return 0;
}

sub prelink_is_wanted {
    return -e '/var/cpanel/dont_remove_prelink';
}

sub prelink_is_installed {

    # qx{} so as to suppress output
    my $check_prelink = qx{/bin/rpm -q prelink 2>&1};

    # If prelink is uninstalled, rpm exits 1.
    return $? ? 0 : 1;
}

sub prelink_is_enabled {
    if ( open my $fh, '<', '/etc/sysconfig/prelink' ) {
        while (<$fh>) {
            return 1 if m{ \A PRELINKING= \s* yes }x;
        }
        close $fh;
    }
    return 0;
}

sub undo_prelink_damage {
    system(qw{/usr/local/cpanel/scripts/check_cpanel_rpms --fix});
}

sub remove_prelink {
    system(qw{/bin/rpm -e --nodeps prelink});
}
