#!/usr/bin/perl
# cpanel - autofixer/nativessl                    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'; }

$SIG{'ALRM'} = sub { die "Install Timeout;" };

alarm 1000;

my @update_perl_modules;

eval { local $SIG{'__DIE__'}; local $SIG{'__WARN__'}; require ExtUtils::Install; };
if ( $@ || $ExtUtils::Install::VERSION < 1.52 ) {
    push @update_perl_modules, 'ExtUtils::Install';
}

eval { local $SIG{'__DIE__'}; local $SIG{'__WARN__'}; require ExtUtils::MakeMaker; };
if ( $@ || $ExtUtils::MakeMaker::VERSION < 6.50 ) {

    push @update_perl_modules, 'ExtUtils::MakeMaker';

    # Special case that has to be updated manually to at least 6.50 to go to latest version
    require Cpanel::HttpRequest;
    my $mm_ver  = '6.50';
    my $src_dir = 'ExtUtils-MakeMaker-' . $mm_ver;

    foreach my $dir ($src_dir) {
        my $file = $dir . '.tar.gz';
        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 $dir ) {
            die "Unable to unarchive source files: $!";
        }
    }

    chdir $src_dir or die "Unable to chdir: $!";
    system 'perl', 'Makefile.PL';
    system 'gmake';
    system 'gmake', 'install';
}

if (@update_perl_modules) {
    system '/scripts/perlinstaller', @update_perl_modules;

    if ( -x '/usr/local/cpanel/bin/nativessl-install' ) {
        system '/usr/local/cpanel/bin/nativessl-install';
    }

}

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