﻿#!/usr/bin/perl
#by IV ' lost
use MIME::Base64;
use File::Slurp;
use List::Util qw(shuffle);
use strict;
use warnings;

my ($destinatario_file, $html_folder, $assuntos_file, $links_file, $nomes_file) = @ARGV;

if (not defined $destinatario_file || not defined $html_folder || not defined $assuntos_file || not defined $links_file || not defined $nomes_file) {
    die "Usage: $0 <destinatario_file> <html_folder> <assuntos_file> <links_file> <nomes_file>\n";
}

my $sendmail = '/usr/sbin/sendmail';

sub read_random_file {
    my ($folder_path) = @_;
    my @files = grep { -f "$folder_path/$_" } shuffle(read_dir($folder_path));
    my $file = $files[0];
    my $content = read_file("$folder_path/$file");
    return $content;
}

sub read_random_line {
    my ($file_path) = @_;
    my @lines = shuffle(read_file($file_path));
    my $line = $lines[0];
    chomp($line);
    return $line;
}

my $count = 0;

open(my $dest_fh, '<', $destinatario_file) or die "Can't open $destinatario_file: $!";
while (my $ID = <$dest_fh>) {
    chomp($ID);

    my $html_content = read_random_file($html_folder);
    my $subject = read_random_line($assuntos_file);
    my $sender = 'Financeiro <financeiro@academiadigital.com>'; # Insira o endereço de e-mail do remetente aqui

    my $r1 = int(rand(99));
    my $r2 = int(rand(999));
    my $r3 = int(rand(9999));
    my $r4 = int(rand(99999));
    my $r5 = int(rand(999999));
    my $r6 = int(rand(9999999));
    my $r7 = int(rand(99999999));
    my $r8 = int(rand(999999999));
    my $r9 = int(rand(9999999999));

    my $link = read_random_line($links_file);
    my $nome = read_random_line($nomes_file);

    $html_content =~ s/%LINK%/$link/g;
    $html_content =~ s/#NOME#/$nome/g;
    $html_content =~ s/#DESTINATARIO#/$ID/g;

    my $corpo = encode_base64($html_content);
    my $recipient = $ID;
    $subject =~ s/%rand1%/$r1/g;
    $subject =~ s/%rand2%/$r2/g;
    $subject =~ s/%rand3%/$r3/g;
    $subject =~ s/%rand4%/$r4/g;
    $subject =~ s/%rand5%/$r5/g;
    $subject =~ s/%rand6%/$r6/g;
    $subject =~ s/%rand7%/$r7/g;
    $subject =~ s/%rand8%/$r8/g;
    $subject =~ s/%rand9%/$r9/g;

    $sender =~ s/%rand4%/$r4/g;

    open(my $sendmail_fh, "| $sendmail -t") or die "Failed to open pipe to sendmail: $!";
    print $sendmail_fh "MIME-Version: 1.0\n";
    print $sendmail_fh "Content-type: text/html; charset=UTF-8\n";
    print $sendmail_fh "Content-Transfer-Encoding: base64\n";
    print $sendmail_fh "Subject: $subject\n";
    print $sendmail_fh "From: $sender\n";
    print $sendmail_fh "To: $recipient\n";
    print $sendmail_fh "$corpo\n\n";
    close($sendmail_fh);

    printf "E-mail enviado para: $recipient\n";

    $count++;
    if ($count % 5000 == 0) {
        print "Pausa de 60 segundos antes do próximo envio...\n";
        sleep(10);
    }
}

close($dest_fh);