#!/usr/bin/perl
# cpanel - autofixer/libxml64fix                  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

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

use strict;
use warnings;
use Cpanel::HttpRequest;
use POSIX;

my $machine = ( POSIX::uname() )[4];

my $libdir = '/usr/lib';
if ( $machine =~ /64/ ) {
    $libdir = '/usr/lib64';
}

my $cz_ver  = '2.6.28';
my $file    = 'libxml2-' . $cz_ver . '.tar.gz';
my $src_dir = 'libxml2-' . $cz_ver;

chdir '/usr/local/cpanel/src' or die "Unable to chdir: $!";

if ( !-e $file ) {
    my $url = 'http://' . get_update_source() . '/autofixer/' . $file;
    my $httpClient = Cpanel::HttpRequest->new( 'hideOutput' => 0, 'signed' => 1 );
    $httpClient->download( $url, $file );
    if ( !-e $file ) {
        die "Unable to fetch file $file: $!";
    }
}

system 'tar', 'zxvf', $file;

if ( !-d $src_dir ) {
    die "Unable to unarchive source files: $!";
}

chdir $src_dir or die "Unable to chdir: $!";
system './configure', '--prefix=/usr', '--libdir=' . $libdir;
system 'gmake';
system 'gmake', 'install';

system '/usr/local/cpanel/bin/checkperlmodules';

print "Done\n";

print "<br /><br /><b>You should now restart the cpanel service to fix cpdavd.</b>";

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