#!@PERL@

use strict;
use warnings;
use CGI qw(:standard -utf8);

use lib '@CGIBINDIR@';
use civs_common;
use mail;

my $civs_supervisor = '@SUPERVISOR@';
my $mail_mgmt_url = '@PROTO@://@THISHOST@@CIVSBINURL@/mail_mgmt@PERLEXT@';

my $address = param('address');
my $code = param('code');

print CGI::header(-charset => 'utf-8');

if (!CheckAddr($address)) {
    print start_html(), p("Illegal mail address <$address>");
    exit 0;
}

&AcquireGlobalLock;

my $optouts = &GetOptouts();
my $opted_out = &HasOptOuts($optouts, $address);

# The activation code for this address
sub ActivationCode {
    my ($address) = @_;
    $address = &CanonicalizeAddr($address);
    if (!defined($private_host_id)) {
        &GetPrivateHostID;
    }
    return civs_hash('activation', $address, $private_host_id);
}

# Canonicalize an activation code.
# Trims off leading and trailing whitespace.
sub CleanCode {
    my ($code) = @_;
    $code =~ s/^(\s)+//;
    $code =~ s/(\s)+$//;
    return $code;
}

if (!defined($code)) {
# This is a request to send a code

    &ReleaseGlobalLock;

    if ($opted_out) {
        print start_html(), p($tx->cant_send_email), end_html();
        exit 0;
    }

    my $code = &ActivationCode($address);

    if ("@LOCALDEBUG@") {
        print "OK Would email activation code $code to $address at this point."
    } else {
        OpenMail;

        if (MailFrom('@AUTH_SENDER@') && MailTo($address) && StartMailData()) {
            my $uniqueid = &SecureNonce;
            my $message_id = "CIVS-activation.$uniqueid\@$thishost";

            SendHeader('From', $tx->From_CIVS($civs_supervisor));
            SendHeader('Sender', $civs_supervisor);
            SendHeader('Reply-To', $civs_supervisor);
            SendHeader('Message-ID', "<$message_id>");
            SendHeader('To', "<$address>");
            SendHeader('Subject', $tx->activation_code_subject);
            SendHeader('Content-Transfer-Encoding', '8bit');
            SendHeader('Return-Path', $civs_supervisor);
            SendHeader('X-Mailer', 'CIVS');
            Send('');
            Send($tx->someone_has_requested_activation($address, $code, $mail_mgmt_url));
            EndMailData;
        }
        CloseMail;
        print "OK";
    }
} else {
# This is a request to use a code.
    $code = &CleanCode($code);
    my $expected_code = &ActivationCode($address);
    if ($code eq $expected_code) {
        my $report;
        if (UserActivated($optouts, $address)) {
            $report = 'already ' . $tx->already_activated;
        } else {
            $report = 'activated ' . $tx->activation_successful;
        }
        my $pats = SetOptOutPatterns($optouts, $address, '+');
        SaveOptOuts($optouts);
        my $key = &OptOutKey(&CanonicalizeAddr($address));
        my $fname = "@CIVSDATADIR@/invites/$key";
        my @rows = ();
        my $invites = "";
        my %invitations;
        if (open(INVITES, "<", $fname)) {
            $invites = <INVITES>;
            my @lines = split /\n/, $invites;
            for my $line (@lines) {
                $line =~ s/(\s)+$//;
                (my $url, my $title) = split / /, $line, 2;
                if (!defined($invitations{$url})) {
                    $invitations{$url} = 1;
                    push @rows, [$url, $title];
                }
            }
            close(INVITES)
        }
        print $report, ' ', $tx->pending_invites($pats, \@rows);
    } else {
        print 'failed ', $tx->codes_dont_match;
        if ("@LOCALDEBUG@") {
            print "<br>Expected code: $expected_code";
        }
    }
    &ReleaseGlobalLock;
}

1;
