#!/usr/bin/perl
#
#
use strict;
use Getopt::Std;
use Sys::Syslog;
use IO::Socket;
use IO::Socket::SSL;
use File::Temp qw/tempfile/;
use IO::File;
use Mail::POP3Client;
use Email::Simple;
use Carp;

my $VERSION = '2.8.6';

my %opts;
getopts('DVdhSsvA:c:H:M:P:R:n:p:r:i:u:X:x:',\%opts);

version_exit() if $opts{V};
help_exit() if $opts{h};

my $DEBUG    = $opts{D};
my $VERBOSE  = $opts{v};

my %conf;
if ($opts{c}) {
   %conf = read_config($opts{c}); 
}

my $user      = $opts{u} || $conf{user};
my $pass      = $opts{p} || $conf{pass};
my $host      = $opts{H} || $conf{host}      || 'localhost';
my $port      = $opts{P} || $conf{port};
my $runuser   = $opts{R} || $conf{runuser}   || 'benno';
my $ssl       = $opts{s};
my $authmode  = $opts{A} || $conf{authmode}  || 'BEST';

my $suppress_verify = $opts{S}   || $conf{suppress_verify};

help_exit() if not ($user and $pass);

my $ERRMSG;

$0 = "benno_pop3auth -H $host -P $port";

LWs::RunAs->import($runuser);

my $pop;
eval{
    my $sock = open_socket($host,$port,$ssl,$suppress_verify);
    if ($ssl and ($authmode eq 'BEST')) { $authmode = 'PASS'; }

    # all parameters as method or all on new(...)!
    # see: FS#1000
    $pop = Mail::POP3Client->new();
    $pop->User($user);
    $pop->User($user);
    $pop->Pass($pass);
    $pop->Socket($sock);
    $pop->AuthMode($authmode);
    $pop->Debug($DEBUG);

    if (!$pop->Connect) {
        $ERRMSG = $pop->Message;
        die "Cannot connect to $host: $ERRMSG\n";
    }
    if (!$pop->Login) {
        $ERRMSG = $pop->Message;
        die "Login failed: $ERRMSG\n";
    }
};
if ($@) {
    print "ERR AUTH\n";
}


### EOP ###
1;

package LWs::RunAs;

use strict;

sub import {
    my ($package,$user) = @_;
    unless( $user ){
        print STDERR __PACKAGE__." must be imported with user to run as.\n";
        exit 1;
    }
    if (($< == 0) || (getpwuid($<) eq $user)) {
        my ($uid,$gid) = (getpwnam($user))[2,3];
        $( = $gid;
        $) = $gid;
        $> = $uid;
        $< = $uid;
    }
    else {
        print STDERR "Program must be run as $user or root.\n";
        exit 2;
    }
}


package LWs::SingleInstance;

use strict;

use Fcntl ':flock';

#
# Exit program if more than one instance is runningg
#
INIT {
    if (tell(*main::DATA) == -1) {
        # __DATA__ handle not available
        print STDERR "$0 needs an __END__ literal at the end of the file.\n";
        exit 2;
    }
    elsif (!flock main::DATA, LOCK_EX | LOCK_NB) {
        # cannot lock __DATA__ "file"
        print STDERR "An instance of $0 is already running.\n";
        exit 1;
    }
}

### EOP ###
1;

__END__

