#!/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 $DEBUG       = $ENV{DEBUG};
my $domainlist  = $ENV{domain_list} || '/etc/benno-web/restauth-domains.conf';

my $error = 0;
my %domains;

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

my ($bennouser,$bennopass);
if (!$secondline) {
    # AUTHPROTO: STDIN
    ($bennouser,$bennopass) = split /\s+/,$firstline,2;
}
else {
    # AUTHPROTO: STDIN2
    $bennouser = $firstline;
    $bennopass = $secondline;
}
if (!$bennopass) {
    print "ERROR ERR_NOPASS\n";
    print STDERR "Aufruf: echo -e \"<username>\n<passwort>\" | $0\n";
    exit 1;
}

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;
}

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

    if ($domain eq $listdomain) {
        $rest_url       = $authurl;
        $rest_key       = $apikey;
        $rest_container = $container;
        last;
    }
    if ($listdomain eq '*') {
        $default_url = $authurl;
        $default_key = $apikey;
    }
}
close $dl;
my $url = $rest_url || $default_url;
my $key = $rest_key || $default_key;

unless ($url || $key) {
    print STDERR "[RESTAUTH:2] User domain \"$domain\" not found in domainlist $domainlist\n" if $DEBUG >= 2;
    exit 0;
}

eval {
    print "ARCHIVE $rest_container\n";
    print rest_auth($url,$key,$bennouser,$bennopass);
};
if ($@) {
    print STDERR "ERROR remote error at $url: $@\n";
    print "ERR_INTERN\n";
}


### 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 ###

