#!/usr/bin/perl -w
######################################################################
# emailregc.pl
######################################################################
# Perl Power! - Michael Schilli 1998
######################################################################

use Net::POP3;                      # mail interrogation handler
use Fcntl qw/:flock/;               # define LOCK_EX

my $efile = '/usr/data/email.dat';  # address file

my $activ = 0;                      # statistics

$host   = 'localhost';              # mail host
$userid = 'register';               # registration mail account
$passwd = 'topsecret!';             # password

$verbose = 0;                       # talkative?
@ARGV = grep { !(/^-v$/ && ($verbose = 1)) } @ARGV;

                                    # read mail
($mail = Net::POP3->new($host)) || die "Could not open $host";

$nof_messages = $mail->login($userid, $passwd);
die "Userid/Passwd Error" unless defined $nof_messages;

if($nof_messages) {                 # are there any messages?
                                    # for all messages
    foreach $mesgno (keys %{$mail->list()}) {
                                    # scour all header fields
        foreach (@{$mail->top($mesgno)}) {
            $key = $1 if                    # key in subject field
                /Subject: Re: Your registration \(key: (.*)\)/;
            $from = $1 if(/From: (.*)/);    # find sender
        }

        activate_entry($from, $key) &&      # activate
            $mail->delete($mesgno) &&       # delete mail
            $activ++;                       # statistics
    }
}

$mail->quit();                              # exit mail program
print "Mailbox: $nof_messages Activated: $activ\n" if $verbose;

######################################################################
sub activate_entry {               # activate selected entry
######################################################################
    my ($from, $key) = @_;         # sender, key 

    open(FILE, "+<$efile") || die "Cannot open $efile";

    flock(FILE, LOCK_EX);          # protect against parallel access
    seek(FILE, 0, 0);              # go to beginning of file

    while(<FILE>) {                # find sender
        ($cfrom, $ckey) = /(.*) (\S+)$/;
                                   # email and key must match
        if(index($from, $cfrom) && $ckey eq $key) {
            $len = length($ckey);
            seek FILE, -$len-1, 1; # go back by key length
            printf FILE "%${len}s", "OK";  # overwrite key with OK
            print "Activated $cfrom\n" if $verbose;
            close(FILE);
            return(1);             # activated
        }
    }
    close(FILE);
    return 0;                      # entry not found
}

