#!/usr/bin/perl
# 
#
use strict;
my $error = 0;
my %domains;

my $userid  = <>; chomp $userid;
my $iss     = <>; chomp $iss;
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 $iss_map = $ENV{oauth2_issmap} || '/etc/benno-oauth2/issuer.map';

open my $maph, $iss_map or $error = $!;
if ($error) {
    print STDERR "Cannot access issmap file \"$iss_map\": $!\n";
    exit 1;
}

my $auth_ok = 0;
my $e_found = 0;
while (my $line = <$maph>) {
    next if $line =~ /^#/;
    next if $line =~ /^$/;
    chomp $line;

    my ($mapiss,$mapcontainer) = $line =~ m!^(\*|https://\S+)\s+(\S+)!i;
    $mapiss =~ s!/$!!;  $mapiss = lc $mapiss;
    $iss =~ s!/$!!;     $iss = lc $iss;

    if (($mapiss eq $iss) or ($mapiss eq '*')) {    # map issuer or asterisk wildcard
        $auth_ok = 1;
        print "ARCHIVE $mapcontainer\n";
        next;
    }

    if ($mapiss eq '*') {
        $auth_ok = 1;
        print "ARCHIVE $mapcontainer\n;"
    }
}
close $maph;

if ($auth_ok) {
    print "AUTH OK\n";
    print "AUTH LAST\n";
    exit;
}

print STDERR "WARN issuer url \"$iss\" not found in $iss_map\n";

