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

BEGIN { unshift @INC, '/usr/local/cpanel'; }

die "No yum.conf found!\n" if !-e '/etc/yum.conf';

require Cpanel::SafeRun::Simple;
require Cpanel::SafeFile;

my $perl_rpm_verify = Cpanel::SafeRun::Simple::saferun( 'rpm', '-V', 'perl' );
my $perl_modified = grep( /\s\/usr\/bin\/perl$/, split( /\n/, $perl_rpm_verify ) );

# Add subversion and samba excludes
if ($perl_modified) {
    my $la = Cpanel::SafeFile::safeopen( \*YC, '<', '/etc/yum.conf' );
    if ($la) {
        my @UP;
        my $has_exclude = 0;
        while ( my $line = <YC> ) {
            chomp $line;
            if ( $line =~ m/^\s*exclude\s*=/i ) {
                $has_exclude = 1;
                if ( $line !~ m/subversion/ ) {
                    $line .= ' subversion*';
                }
                if ( $line !~ m/samba/ ) {
                    $line .= ' samba*';
                }
            }
            push @UP, $line . "\n";
        }
        Cpanel::SafeFile::safeclose( \*YC, $la );

        my $lb = Cpanel::SafeFile::safeopen( \*UPDATEW, '>', '/etc/yum.conf' );
        if ( !$lb ) {
            die "Could not write to /etc/yum.conf";
        }
        foreach (@UP) {
            if (m/^\[main\]/i) {
                print UPDATEW;    # Conserve [main]
                if ( !$has_exclude ) {
                    print UPDATEW "exclude=subversion* samba*\n";
                }
            }
            else {
                print UPDATEW;
            }
        }
        Cpanel::SafeFile::safeclose( \*UPDATEW, $lb );
    }
    else {
        die "Unable to update yum.conf: $!";
    }
}

# Allow perl update and checkperlmodules
else {
    my @INSTALLEDMODS = split( /\n/, `/scripts/perlmods -l` );
    @INSTALLEDMODS = grep( !/^CPAN=/, @INSTALLEDMODS );

    system '/scripts/checkyum', '--noperl';
    system 'yum', '-y', 'update', 'perl';
    system '/scripts/checkyum';

    system '/scripts/checkperlmodules', '--force';
    if ( @INSTALLEDMODS && -x '/scripts/perlinstaller' ) {
        print "Restoring Modules ....";
        my @MODS;
        foreach my $mod (@INSTALLEDMODS) {
            my ( $modname, $ver ) = split( /=/, $mod );
            push @MODS, $modname;
        }
        system '/scripts/perlinstaller', '--force', @MODS;    #we might have changed the malloc
        system '/scripts/perlinstaller', @MODS;               #twice
        system '/scripts/perlinstaller', @MODS;               #then again
        print "Done\n";
    }
}
