#!/usr/bin/perl
# cpanel - autofixer/phpconfig                    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;
require Cpanel::PHPConfig;

print "Verifying that Cpanel::PHPConfig can handle PHP 5.2.10 ... ";

if ( $Cpanel::PHPConfig::VERSION >= 1.3 ) {
    print "Complete.\n";
    exit;
}
else {
    print "Updating Cpanel::PHPConfig.\n";
}

require Cpanel::HttpRequest;

my $url            = 'http://' . get_update_source() . '/autofixer/PHPConfig.pm.1.3';
my $phpconfig_file = '/usr/local/cpanel/Cpanel/PHPConfig.pm';

my $httpClient = Cpanel::HttpRequest->new( 'hideOutput' => 0, 'signed' => 1 );
$httpClient->download( $url, $phpconfig_file . '.1.3' );
if ( !-e $phpconfig_file . '.1.3' || -z $phpconfig_file . '.1.3' ) {
    die "Failed to download $url\n";
}

unlink $phpconfig_file or die "Failed to remove previous $phpconfig_file: $!";
rename $phpconfig_file . '.1.3', $phpconfig_file or die "Failed to update $phpconfig_file: $!";

print "Upgrade complete\n";
exit;

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