#!/usr/bin/perl
# Debug level 0: Send email
# Debug level 1: Send email to myself
# Debug level 2: Print names and email addresses

use strict;
use warnings;

use Text::CSV;
use Email::MIME::CreateHTML;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP;
use Email::Sender::Transport::SMTPS;
use Email::Sender::Transport::SMTP::TLS;
use Term::ReadKey;
use File::Basename;
use Try::Tiny;
use Data::Dumper;

my $map_dir = '/home/tim/Documents/Projects/2019/Gun Run/Maps/';
my $email_csv = "$map_dir/GIS Base Map/marshals_by_position.csv";
my $debug     = 2;
my @emails;

if ($debug == 2) {
    print "WARNING: Printing names. Not sending emails!\n";
} elsif ($debug == 1) {
    print "WARNING: Sending emails to a TEST address.\n";
} elsif ($debug == 0) {
    print "Sending emails to...\n";
} else {
    print "ERROR: Invalid debug value\n";
}

my $password;
if (-f "$map_dir/password_store") {
    open(my $fh, '<:encoding(UTF-8)', "$map_dir/password_store") or die "Could not open password store: $!";
    while (my $row = <$fh>) {
        chomp($password = $row);
    }
    close($fh)
} else {
    print "Please type your email password: ";
    #chomp($password = <STDIN>);
    ReadMode('noecho');
    chomp($password = ReadLine(0));
    print "\n";
    ReadMode('normal');
}

my $csv = Text::CSV->new ( { binary => 1 } ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $ifh, "<", $email_csv or die "Could not read $email_csv: $!";
$csv->column_names($csv->getline( $ifh ));
while ( my $row = $csv->getline( $ifh ) ) {
	my $person = {
		"position" => $row->[0],
		"club" => $row->[1],
		"first_name" => $row->[2],
		"name" => $row->[4],
		"email" => $row->[6],
	};
	$person->{"name"} =~ s/ +$//g  if $person->{"name"};
	$person->{"name"} =~ s/  +/ /g if $person->{"name"};
	$person->{"first_name"} =~ s/ +$//g  if $person->{"first_name"};
	$person->{"first_name"} =~ s/  +/ /g if $person->{"first_name"};
	$person->{"email"} =~ s/,//g   if $person->{"email"};
	push @emails, $person;
}
$csv->eof or $csv->error_diag();
close $ifh;

#@emails = sort { $a->{"position"} cmp $b->{"position"}  } @emails;
if ($ARGV[0]) {
	my $pos = $ARGV[0];
	@emails = grep { $_->{"position"} =~ /^$pos$/ } @emails;
}
#print Dumper(@emails);

foreach my $person (@emails) {
	next unless $$person{"name"} and $$person{"email"};
	next unless $$person{"club"} =~ /^(AAC)$/;
        next if $$person{"position"} =~ /\D/;
	my $salutation = $$person{"first_name"};
	my $name = $$person{"name"};
	my $email = $$person{"email"};
        my $club = $$person{"club"};
	next unless $email =~ /@/;
	my $position = $$person{"position"};

	foreach my $m (split(/[, ]+/, $email)) {
		$m = "$name <$m>";
		printf "%-4s %-15s %15s\n", $$person{"position"}, $salutation, $m if ($debug >= 0);
		$m = 'Timothy Allen <tim@allen.org.za>' if ($debug == 1);

		my $html = qq(
<html><head>
</head>
<body>
<p>
Dear $salutation
</p>

<p>
A big thank you from me and from the Gun Run committee for your help marshalling today.
</p>

<p>
It was a very successful Gun Run, and we can all be pleased by how well the event ran. I heard a lot of compliments about the marshalling, and the race went beautifully, I thought, with very few major hiccups.
</p>

<p>
If you have any suggestions as to how we can improve next year, please drop me or Roger an email.
</p>

<p>
I hope you enjoyed the experience and will hopefully support us again next year. Until then, enjoy your running and take care out there.
</p>

<p>
Warm regards,
</p>

<p>
Tim
</p>
</body>
</html>
);

		my $plain_text = qq(Dear $salutation

A big thank you from me and from the Gun Run committee for your help marshalling today.

It was a very successful Gun Run, and we can all be pleased by how well the event ran. I heard a lot of compliments about the marshalling, and the race went beautifully, I thought, with very few major hiccups.

If you have any suggestions as to how we can improve next year, please drop me or Roger an email.

I hope you enjoyed the experience and will hopefully support us again next year. Until then, enjoy your running and take care out there.

Warm regards,

Tim
);

		my $mail = Email::MIME->create_html(
			header => [
				"From" => 'Timothy Allen <tim@allen.org.za>',
				"Subject" => 'Thank you for marshalling',
				"To" => $m,
                                "Reply-To" => 'Timothy Allen <tim@allen.org.za>, Roger Steward <stewardrh@gmail.com>',
			],
			body => $html,
			text_body => $plain_text,
		);
		my $g_transport = Email::Sender::Transport::SMTP::TLS->new(
			host => 'smtp.gmail.com',
			username => 'trallen@gmail.com',
			password => $password,
		);
		my $t_transport = Email::Sender::Transport::SMTP::TLS->new(
			host => 'mail.treehouse.org.za',
			username => 'tim',
			password => $password,
		);
		try {
#			sendmail($mail, { transport => $g_transport }) if ($debug <= 1);
			sendmail($mail, { transport => $t_transport }) if ($debug <= 1);
		} catch {
			warn "\n\nError sending email for position $position\n\n";
			warn $_;
		};
	}
        sleep 2 if ($debug < 1);
	last if ($debug == 1);
}

# vim: set expandtab shiftwidth=4 softtabstop=4 :
