#!/usr/bin/perl
# cpanel - autofixer2/disable_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 DisablePrelink;

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";

    disable_prelink();
    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 disable_prelink {
    local ( $/, $? );

    open my $fh, '<', '/etc/sysconfig/prelink' or die "Couldn't open /etc/sysconfig/prelink for reading: $!";
    my $content = <$fh>;
    close $fh;

    $content =~ s{PRELINKING=\s*yes}{PRELINKING=no};

    open $fh, '>', '/etc/sysconfig/prelink' or die "Couldn't open /etc/sysconfig/prelink for writing: $!";
    print {$fh} $content;
    close $fh;

    system "/etc/cron.daily/prelink > /dev/null 2>&1";
    my $status = $? >> 8;
    return $status == 0 ? 1 : 0;
}
