package Cpanel::Easy::Utils::MD5;

# cpanel - Cpanel/Easy/Utils/MD5.pm               Copyright(c) 2015 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);
use Digest::SHA                     ();
use Cpanel::CPAN::Digest::MD5::File ();

for my $func (@Cpanel::CPAN::Digest::MD5::File::EXPORT_OK) {
    eval qq{
        sub $func {
            shift;
            goto &Cpanel::CPAN::Digest::MD5::File::$func;
        }  
    };
}

sub get_current_path_md5 {
    my ( $self, $path ) = @_;
    return if !-e $path;
    my $md5 = Digest::MD5->new();    # brought in via Cpanel::CPAN::Digest::MD5::File
    -d $path ? $md5->adddir($path) : $md5->addpath($path);
    return $md5->hexdigest();
}

sub set_path_md5 {
    my ( $self, $path ) = @_;
    $path =~ s{\s*(/+\s*)*$}{}g;
    return if $path !~ m{^/};
    my $name = $path;
    $name =~ s{^/}{slash_};
    $name =~ s{/}{_slash_}g;

    open my $save_fh, '>', "$self->{'path_md5_dir'}/$name" or return;
    print {$save_fh} $self->get_current_path_md5($path);
    close $save_fh;
}

sub get_saved_path_md5 {
    my ( $self, $path ) = @_;
    $path =~ s{\s*(/+\s*)*$}{}g;

    my $name = $path;
    $name =~ s{^/}{slash_};
    $name =~ s{/}{_slash_}g;

    open my $save_fh, '<', "$self->{'path_md5_dir'}/$name" or return;
    chomp( my $md5 = readline $save_fh );
    close $save_fh;
    return $md5 if $md5;
    return;
}

sub get_digest {
    my ( $self, $path ) = @_;
    return if !-e $path;

    my $digest;

    # use Digest::SHA if there were sha512 hashes in targz.yaml, otherwise fall back to md5 if possible.
    if ( $self->{'use_sha'} ) {

        # adddir and addpath do not calculate any hashes, they just compile a list of files to hash, so this should be safe
        *Digest::SHA::adddir  = \&Digest::MD5::adddir;
        *Digest::SHA::addpath = \&Digest::MD5::addpath;
        $digest               = Digest::SHA->new(512);
    }
    elsif ( $self->{'use_md5'} ) {
        $digest = Digest::MD5->new();
    }
    else {
        return;
    }

    -d $path ? $digest->adddir($path) : $digest->addpath($path);
    return $digest->hexdigest();

}

1;
