#!/usr/bin/perl
#
# AUTHPROTOCOL: STDIN2
#
use strict;
use Carp;
use DBI;
use lib qw(/usr/share/benno-web);

my $userid  = <>; chomp $userid;
my $issuer  = <>; chomp $issuer;
my $mode    = <>; chomp $mode;

# stop module if standard login request
unless ($mode =~ /^MODE\sOAUTH2$/) {
    print STDERR "Request not from OAuth2\n" if $ENV{DEBUG};
    exit;
}

my $configfile = '/etc/benno-web/benno.conf';
my $config = read_config($configfile);
my $dbh = db_connect($config);

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

my $role = $row->{role};
my $displayname = $row->{displayname};

if (!$row->{'id'}) {
    print STDERR "INFO No additional userdata for \"$userid\" database.\n" if $ENV{DEBUG};
    exit;
}

# Allow to set container if explicitely configured
if ($config->{oauth2_dbcontainer} eq 'yes') {
    my $entrycount = 0;
    my $cnth = $dbh->prepare('SELECT cid,scid FROM container WHERE userid = ?');
    $cnth->execute($userid) or die "DB error: $!\n";
    while (my ($cid,$scid) = $cnth->fetchrow_array) {
        print "ARCHIVE $cid";
        print "/$scid" if $scid;
        print "\n";
        $entrycount++;
    }   
}

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

unless ($email_set) {
    print "MAIL *@*\n" if $role eq 'ADMIN';
    print "MAIL *@*\n" if $role eq 'REVISOR';
}

print "DISPLAYNAME $displayname\n";
print "ROLE $role\n";

### SUBS ######################################################################
# read_config
sub read_config
{
    my $configfile = shift;

    my $config = {};
    open CONF, $configfile or croak "Cannot open config file $configfile. $!\n";
    foreach my $line (<CONF>) {
        next if $line =~ /^$/;
        next if$line  =~ /^#/;
        chomp $line;
        my ($param,$value) = split(/\s*=\s*/,$line,2);
        $config->{$param} = $value;
    }

    return $config;
}


# db_connect
sub db_connect
{   
    my $config = shift;

    my $dbtype = $config->{DBTYPE} || 'sqlite:////var/lib/benno-web/bennoweb.sqlite';
    my $db     = $config->{DATABASE};
    my $dbhost = $config->{DBHOST} || 'localhost';
    my $dbport = $config->{DBPORT} || 3306;
    my $dbuser = $config->{DBUSER};
    my $dbpass = $config->{DBPASS};
    my $DBH;
    if ($dbtype eq 'mysql') {
        eval {
            my $dsn = "DBI:mysql:database=$db;host=$dbhost;port=$dbport";
            $DBH = DBI->connect($dsn,$dbuser,$dbpass);
        };
        if ($@) {
            print STDERR "ERROR: MySQL Driver not installed.\n";
            exit 1;
        }
    }
    else {
        if ($dbtype =~ /^sqlite:\/\/(\/.\S+)$/) {
            my $dsn = "dbi:SQLite:dbname=$1","","";
            $DBH = DBI->connect($dsn);
        }
    }
    return $DBH;
}

