#!/usr/bin/perl
#
# Benno Web AUTH module
#
# Expects:
#  - environment type=storageurl
#  - environment AUTHLINES=ARCHIVE <CONTAINER_NAME>\n...
#
# Returns:
#  - CONTAINER <CONTAINER_NAME>
#  - STORAGEURL <CONTAINER_NAME>
#
use strict;
my $error = 0;
my %domains;

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

my $DEBUG       = $ENV{DEBUG};
my $type        = $ENV{REQUEST_TYPE};
my $storagelist = $ENV{storage_list} || '/etc/benno-import-rest/container-storage.list';

exit 0 unless ($type =~ /^storageurl/);

print STDERR "[CONTAINERSTORAGE:2] Read storagelist $storagelist\n" if $DEBUG >= 2;
my $ContainerURL = read_storagelist($storagelist);


my %containers;
foreach my $line (split /\n/, $ENV{AUTHLINES}) {
    if ($line =~ /^ARCHIVE\s+(.*)$/) {
        $containers{$1} = 1;
    }
}

foreach my $container (keys %containers) {
    foreach my $surl ($ContainerURL->get_urls($container)) {
        print "STORAGEURL $container $surl\n" if $surl;
    }
}


### SUBS ###
sub read_storagelist
{
    my ($listfile) = @_;
    my %containers;
    my $ContainerURL = new ContainerURL;

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

    while (my $line = <$dh>) {
        next if $line =~ /^#/;
        next if $line =~ /^$/;
        $line =~ s/[\r\n]//g;
        my ($container,$storageurl) = split /\s+/, $line;
        $ContainerURL->add_url($container,$storageurl);
    }
    close $dh;

    #return %containers;
    return $ContainerURL;
}

1;
### EOP ###


package ContainerURL;


sub new {
    my $class = shift;

    my $self = {
        containers => {},
    };
    bless $self, $class;

    return $self;
}


sub add_url
{
    my ($self,$container,$url) = @_;

    if (!$self->{containers}->{$container}) {
        $self->{containers}->{$container} = [];
    }
    push @{$self->{containers}->{$container}}, $url;
}


sub get_urls
{
    my ($self,$container) = @_;

    if ($self->{containers}->{$container}) {
        return @{$self->{containers}->{$container}};
    }
}


1;
### EOP ###
