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

alarm(900);

eval ' use Encode::Detect::Detector (); ';

if ($@) {
    require Cpanel::HttpRequest;
    my $cz_ver    = '1.01';
    my $file      = 'Encode-Detect-' . $cz_ver . '.tar.gz';
    my $src_dir   = 'Encode-Detect-' . $cz_ver;
    my $xsfiledir = 'ExtUtils-ParseXS-2.19';

    foreach my $dir ( $src_dir, $xsfiledir ) {
        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', '-I../ExtUtils-ParseXS-2.19/lib', 'Makefile.PL';
    system 'gmake';
    system 'gmake', 'install';

    print "Done\n";
}

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