#!/usr/local/bin/perl5.24.0

use common::sense;
use warnings;

use Net::LDAP;
use Log::Log4perl qw(:easy);
use JSON::XS;
use Data::Dumper;
use Encode qw(encode decode);

my $keydir = '/opt/openvpn/ca/keys/';

# File where secrets are stored, one per line in the format "key:secret". The
# secret must not end with a whitespace character.
#
my $default_secret_path = "/opt/openvpn/etc/secrets";

# Get a secret from the specified file (or, default, $default_secret_path) that
# is tagged with `key'. If it is not found or the file cannot be opened, die.
#
sub get_secret {
        my ($key, $filename) = @_;
        $filename ||= $default_secret_path;

        open(my $fh, "<", $filename) or
          die("get_secret(): cannot open secrets file '$filename': $!");
        my $pattern = quotemeta($key);
        while (defined(my $line = <$fh>)) {
                $line =~ s/\s+$//;               # trim trailing blanks
                if ($line =~ /^$pattern:(.*)/o) {
                        close($fh);
                        return $1;
                }
        }
        close($fh);                     # maybe something catches the die()
        die("get_secret(): key '$key' not found in $filename");
}

my %userkeys = map { $_ =~ s/^$keydir//o; $_ =~ s/\.key$//; $_ => 1; } glob("$keydir*.key");

# Initializing Logmessages

my $JSON = JSON::XS->new;

my $ldapServer = 'ldap://127.0.0.1:489';
$ldapServer = 'ldapi://%2Fvar%2Frun%2Fslapd%2Fslapd.sock';
my $ldapUser = 'uid=adminnw,cn=People,dc=charite.de';
my $ldapPassword = get_secret("ldap/adminnw");

my @ldapAttributes = qw(
    uid
    nwHasLimes
);

my $ldap = Net::LDAP->new($ldapServer);

if (! defined $ldap) {
    die();
}

my $mesg = $ldap->bind(
    dn => $ldapUser,
    password => $ldapPassword
);

if (! defined $mesg->code()) {
    die("ERROR - bind failed: ", $mesg->error_text((),"\n"));
}

$mesg = $ldap->search(
    base	=> 'cn=People,dc=charite.de',
    filter	=> 'uid=*',
    attrs	=> \@ldapAttributes,
);

if (! defined $mesg->code()) {
    die($mesg->error);
}


foreach my $entry ($mesg->entries()) {
    my $username = $entry->get_value("uid");
    
    if (! $entry->get_value("nwHasLimes")) {
	if (exists $userkeys{ $username }) {
	    say $username;
	}
    }
}

$mesg = $ldap->unbind;
