# Copyright (c) 2021-2024 Andrew Ruthven <andrew@etc.gen.nz>
# Portions Copyright (c) Best Practical Solutions, LLC
#   <sales@bestpractical.com>, licensed under the GPL v2.
#
# Test logging in using an LDAP user that doesn't exist in the
# database, should be copied over.
BEGINPERL
if ($debug) { $ENV{'LDAP_DEBUG'} = 1 };

use Net::LDAP::Server::Test;
use Net::LDAP;
use IO::Socket::INET;

my $ldap_port = 21394;
my $ldap_socket = IO::Socket::INET->new(
    Listen    => 5,
    Proto     => 'tcp',
    Reuse     => 1,
    LocalPort => $ldap_port,
);

# Keep it around after this block exits.
$evaled{'ldap_server'} = Net::LDAP::Server::Test->new( $ldap_socket, auto_schema => 1 );

my $ldap = Net::LDAP->new("localhost:$ldap_port") || die "Failed to instantiate Net::LDAP: $!";
$ldap->bind();
my $base   = "dc=example,dc=com";
my $users  = "ou=users,$base";
my $groups = "ou=groups,$base";
$ldap->add( $base );

for my $username (qw/ldap3 ldap4/) {
    my $dn       = "uid=$username,$users";
    my $entry    = {
        cn           => $username,
        mail         => "$username\@example.com",
        uid          => $username,
        objectClass  => 'User',
        userPassword => $username,
    };
    $ldap->add( $dn, attr => [%$entry] );
}

# We need to keep the client around, otherwise the test server will exit.
$evaled{'ldap_client'} = $ldap;
#sleep 100;
ENDPERL

TYPE=PROPFIND
URL=http://regression_ldap.host/caldav.php/
HEADER=Content-Type: text/xml
HEADER=Depth: 1
AUTH=ldap3:ldap3
HEAD

BEGINDATA
<?xml version="1.0" encoding="utf-8" ?>
<D:propfind xmlns:D="DAV:">
  <D:prop>
    <D:resourcetype/>
  </D:prop>
</D:propfind>
ENDDATA

# Check that a usr record has been created.
QUERY
SELECT active, email, fullname, last_used, password, username
FROM usr
WHERE username = 'ldap3';
ENDQUERY

