#!/usr/bin/perl
# cpanel - autofixer2/redhat_pathtools            Copyright(c) 2014 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::redhat_pathtools;

use strict;
use warnings;
use Config;

exit( script() ) unless caller();

sub script {

    # We're only doing this on RHEL 5 distros.
    get_rpm_distro_version() =~ m/5/ or return 0;

    # Only try to fix an overwrite of Cwd from yum if Cwd.so is segfaulting.
    is_pathtools_broken() or return 0;
    print "PathTools (Cwd / File::Spec) are broken. Bugzilla 1150717. Attempting to repair\n\n";

    # Remove the PathTools provided files to fully revert back to the rpm version.
    my $cpan_base_install = $Config{'installarchlib'} or die "\%Config is broken. Re-install perl.";
    foreach my $file (qw{File/Spec File/Spec/Cygwin File/Spec/Epoc File/Spec/Functions File/Spec/Mac File/Spec/OS2 File/Spec/Unix File/Spec/VMW File/Spec/Win32}) {
        unlink "$cpan_base_install/$file.pm";
    }
    print "Reverted to the RPM version of PathTools files. Attempting to re-install the newer version from CPAN\n\n";

    # Try to re-install Cwd.
    system( '/scripts/perlinstaller', 'Cwd' );
    return 0;
}

sub is_pathtools_broken {
    my $output = `/usr/bin/perl -MExtUtils::MakeMaker -e1 2>&1`;
    return $output =~ m/\QAttempt to free unreferenced scalar\E/ms ? 1 : 0;
}

sub get_rpm_distro_version {
    my @version_output = `/bin/rpm -qf --queryformat '%{VERSION}\n' '/etc/redhat-release'`;

    my $version = shift @version_output or return 'unknown';

    # If multiple lines, call it unknown if they all don't begin with the same number
    return 'unknown' if ( @version_output && grep { $_ ? ( substr( $_, 0, 1 ) ne substr( $version, 0, 1 ) ) : 0 } @version_output );

    # Unknown if the first character is not 5 or 6 (The only major distros we support)
    $version =~ m/^([56])/ or return 'unknown';

    # Return the first character.
    return "$1";
}

1;
