#!/usr/bin/perl
#
# AUTHPROTOCOL: STDIN2
#
use strict;
use DBI;
use Digest::MD5;

if ($ENV{AUTHOK}) {
    print STDERR "Already authenticated, skip $0\n" if $ENV{DEBUG};
    exit 0;
}

if ($ARGV[0]) {
    print STDERR "Keine Argumente erlaubt.\n";
    print STDERR "Aufruf: echo \"USERNAME PASSWORT\" | $0\n";
    exit 1;
}

my $firstline  = <STDIN>;
my $secondline = <STDIN>;
chomp $firstline;
chomp $secondline;

my ($username,$password);
if (!$secondline) {
    # AUTHPROTO: STDIN
    ($username,$password) = split /\s+/,$firstline,2;
}
else {
    # AUTHPROTO: STDIN2
    $username = $firstline;
    $password = $secondline;
}

if (!$password) {
    print "ERROR ERR_NOPASS\n";
    print STDERR "Aufruf: echo -e \"<username>\n<passwort>\" | $0\n";
    exit 1;
}

my $dbpath = '/var/lib/benno-web/bennoweb.sqlite';

my $dbh = DBI->connect("dbi:SQLite:dbname=$dbpath");

my $sth = $dbh->prepare('SELECT * FROM user WHERE id = ?');
$sth->execute($username); 
my $row = $sth->fetchrow_hashref;

my $passwd_db   = $row->{'password'};
my $ctx = Digest::MD5->new;
$ctx->add($password);
my $passwd_md5= $ctx->hexdigest;

if ($passwd_md5 ne $passwd_db) {
    print "ERROR ERR_AUTH\n";
    print STDERR "Passwort fuer User $username falsch.\n" if $ENV{DEBUG};
    exit 1;
}

print 'DISPLAYNAME '.$row->{'name'}."\n";
print 'ROLE '.$row->{'role'}."\n";

eval {
    my $cnth = $dbh->prepare('SELECT cid,scid FROM container WHERE userid = ?');
    $cnth->execute($username) or die "DB error: $!\n";
    while (my ($cid,$scid) = $cnth->fetchrow_array) {
        print "ARCHIVE $cid";
        print "/$scid" if $scid;
        print "\n";
    }
};
if ($@) { # dbversion < 2019100701
    foreach my $archive (split /,\s*/, $row->{archive}) {
        print 'ARCHIVE '.$archive."\n";
    }
}

my $sth = $dbh->prepare('SELECT address FROM address WHERE id = ?');
$sth->execute($username); 
my @adresslist;
while (my $row = $sth->fetchrow_hashref) {
    print 'MAIL '.$row->{'address'}."\r\n";
}

print "AUTH OK\n";
print "AUTHPARAM AUTHBY db\n";

