package Cpanel::Easy::Utils::HttpUpdate;

# cpanel - Cpanel/Easy/Utils/HttpUpdate.pm        Copyright(c) 2016 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cpanel license. Unauthorized copying is prohibited

use strict;
use warnings;
no warnings qw(redefine);

sub fetch_from_httpupdate_silent {
    my ( $self, %args ) = @_;

    # quiet the output (yes there's output from HttpRequest,
    # even with 'hideOutput' => 1), use IO::Redirect ???

    no warnings;

    open( OLDOUT_A, '>&STDOUT' ) or die "Can't dup STDOUT: $!";
    open( OLDERR_A, '>&STDERR' ) or die "Can't dup STDERR: $!";

    $self->print_to_log("\n!! Start: Silent httpupdate request !!\n\n");
    open( STDOUT, ">>$self->{'log_file'}" ) or die "Can't redirect STDOUT: $!";
    open( STDERR, ">>$self->{'log_file'}" ) or die "Can't redirect  : $!";

    my $rc = $self->fetch_from_httpupdate(%args);

    open( STDOUT, '>&OLDOUT_A' ) or die "Can't restore OLDOUT_A: $!";
    open( STDERR, '>&OLDERR_A' ) or die "Can't restore OLDERR_A: $!";

    $self->print_to_log_and_screen("Failed to download $args{url} : $@\n") if $@;
    $self->print_to_log("\n!! End: Silent httpupdate request !!\n\n");

    return $rc;
}

sub fetch_from_httpupdate {
    my ( $self, %args ) = @_;
    require Cpanel::HttpRequest;    # only use it if/when we need it...

    my $string;
    my $actual_server = '';

    eval {
        my $req = Cpanel::HttpRequest->new( 'hideOutput' => 1 );
        $string        = $req->request(%args);
        $actual_server = $req->{connectedHostAddress};    # stored by Cpanel::HttpRequest when there are multiple hosts serving a file
    };

    if ( $@ && ( caller(1) )[3] !~ m{fetch_from_httpupdate_silent} ) {
        $self->{'_'}{'prefs'}{'verbose'} ? $self->print_to_log_and_screen("Failed to download $args{url} : $@\n") : $self->print_to_log("Failed to download $args{url} : $@\n");
    }

    if ( $actual_server && $args{destfile} ) {
        $self->print_to_log("!! File downloaded from $actual_server and written to $args{destfile}");
    }

    return if $@;
    return if !defined $string;
    return $string || 1;
}

1;
