#!/usr/bin/perl
# DBD::mysql fix for older version of Red Hat (i.e. 7.3)

use strict;
use warnings;

my $do_update = 0;
my $dbd_ver   = '3.0007';

undef $@;
eval { require DBD::mysql; };

if ($@) {
    $do_update = 1;
}
elsif ( $DBD::mysql::VERSION ne $dbd_ver ) {
    $do_update = 1;
}

if ( !$do_update ) {
    print <<"EOM";
DBD::mysql is version $DBD::mysql::VERSION
No update needed.
EOM
    exit 0;
}

## audit case 45000: leaving this references to EDGE as is; presumably,
##   this autofixer has served its purpose
system '/scripts/cpanelsync', get_update_source(), '/cpanelsync/EDGE/src', '/usr/local/cpanel/src';

if ( !-e '/usr/local/cpanel/src/3rdparty/perl/DBD-mysql-' . $dbd_ver . '.tar.gz' ) {
    print <<"EOM";
Unable to fetch DBD::mysql sources.
Sorry, fix is impossible.
Please contact cPanel support.
EOM
    exit 1;
}
elsif (!-e '/usr/local/cpanel/src/3rdparty/perl/patches/DBD-mysql-' . $dbd_ver . '.patch.sh'
    || !-e '/usr/local/cpanel/src/3rdparty/perl/patches/dbdmysql.patch' ) {
    print <<"EOM";
Unable to fetch DBD::mysql patch.
Sorry, fix is impossible.
Please contact cPanel support.
EOM
    exit 1;
}

chdir '/usr/local/cpanel/src/3rdparty/perl' or die "Unable to chdir: $!";
system 'gmake', 'dbdmysql';
if ( !-e 'DBD-mysql-' . $dbd_ver . '/blib/arch/auto/DBD/mysql/mysql.so' ) {
    print <<"EOM";
Unable to build DBD::mysql $dbd_ver.
Sorry, fix is impossible.
Please contact cPanel support.
EOM
    exit 1;
}
else {
    system 'gmake', 'dbdmysqlinstall';
    system 'gmake', 'dbdmysqldistclean';
    print <<"EOM";

DBD::mysql $dbd_ver has been updated successfully.

EOM
}

sub get_update_source {
    my $update_source = 'httpupdate.cpanel.net';
    my $source_file   = '/etc/cpsources.conf';
    if ( -r $source_file && -s $source_file ) {    # pull in from cpsources.conf if it's set.
        open( my $fh, "<", $source_file );
        while (<$fh>) {
            next if ( $_ !~ m/^\s*HTTPUPDATE\s*=\s*(\S+)/ );
            $update_source = "$1";
            die("HTTPUPDATE is set to '$update_source' in $source_file") if ( !$update_source );
            last;
        }
    }

    return $update_source;
}
