#!/usr/bin/perl
#
# Benno Web AUTH module
#
# Expects:
#  - <username>\n<password>
#
# Returns:
#  - AUTH OK
#  - ERROR <ERRSYM>
#  - nothing (not affected for domain)

use strict;
use HTTP::Tiny;

my $error = 0;
my %domains;

my $bennouser = <>; chomp $bennouser;
my $bennopass = <>; chomp $bennopass;

my $DEBUG       = $ENV{DEBUG};
my $domainlist  = $ENV{domain_list} || '/etc/benno-web/restauth-domains.list';

my $domain      = (split /\@/, $bennouser, 2)[1];

print STDERR "[RESTAUTH:2] Check $domain in domainlist $domainlist\n" if $DEBUG >= 2;


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

while (my $line = <$dl>) {
    next if $line =~ /^#/;
    next if $line =~ /^$/;
    $line =~ s/[\r\n]//g;
    my ($listdomain,$authurl,$apikey) = split /\s+/, $line;

    if ($domain eq $listdomain) {
        eval {
            print rest_auth($authurl,$apikey,$bennouser,$bennopass);
        };
        if ($@) {
            print STDERR "ERROR remote error at $authurl: $@\n";
            print "ERR_INTERN\n";
        }
        last;
    }
}
close $dl;


### SUBS ###
sub rest_auth
{
    my ($endpoint_url,$apikey,$user,$pass) = @_;


    my $options =  {
        content => "$user\n$pass\n",
    };
    my $default_headers = {
        'Accept' =>  'text/plain',
    };

    my $http = HTTP::Tiny->new(default_headers => $default_headers,);

    my $rurl = "$endpoint_url?apikey=$apikey";
    my $response = $http->post($rurl,$options);

    if ($response->{status} !~ /^2/) {
        die "$endpoint_url status (HTTP $response->{status})";
    }

    if (length $response->{content}) {
        return $response->{content};
    }
    else {
        die "cannot authenticate: no response data\n";
    }

}


1; ### EOP ###

