#!/usr/bin/perl
# cpanel - autofixer/net_smtp_fix                 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::HttpRequest;

print "This autofixer will downgrade PHP's pear Net_SMTP if needed.\n";

my $ident_string  = 'SMTP.php 2180 2008-12-18';                                              # String found in broken version
my $url           = 'http://' . get_update_source() . '/autofixer/Net_SMTP.php.2008.6.10';
my $net_smtp_file = '/usr/local/cpanel/src/Net_SMTP/SMTP.php';

# Determine if any downgrades required
my @locations = qw( /usr/local/cpanel/3rdparty/lib/php/Net/SMTP.php /usr/local/cpanel/base/3rdparty/roundcube/program/lib/Net/SMTP.php );

my @downgrade;
foreach my $location (@locations) {
    if ( open my $fh, '<', $location ) {
        while ( my $line = readline $fh ) {
            last if $line =~ m/^require_once\s/;                                             # Marks the end of the header containing the ident string
            next if $line !~ m/\Q$ident_string\E/;
            push @downgrade, $location;
            last;
        }
        close $fh;
    }
}

if ( !@downgrade ) {
    print "No downgrade required.\n";
    exit;
}

if ( !-e $net_smtp_file ) {
    if ( !-e '/usr/local/cpanel/src/Net_SMTP' ) {
        mkdir '/usr/local/cpanel/src/Net_SMTP';
    }
    my $httpClient = Cpanel::HttpRequest->new( 'hideOutput' => 0, 'signed' => 1 );
    $httpClient->download( $url, $net_smtp_file );
    if ( !-e $net_smtp_file ) {
        die "Failed to download $url\n";
    }
}

foreach my $location (@downgrade) {
    system 'cp', '-fv', $net_smtp_file, $location;
}

print "\nDowngrade complete\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;
}
