#!/bin/bash
#
# Copyright (C) 2020 Radosław Korzeniewski
# License: BSD 2-Clause; see file LICENSE-FOSS
#

TestName="ldap-auth-plugin-test"
. scripts/functions
. scripts/regress-utils.sh

mkdir -p ${tmp}

scripts/cleanup
scripts/copy-ldap-auth-plugin-confs

start_local_slapd

# Authentication Plugin = "ldap:binddn=@BINDDN@ bindpass=@BINDPASS@ url=ldap://localhost:3890 query=@LDAPQUERY@"
db_name=$(cat ${tmp}/ldap_db_name)
BINDDN="cn=root,dc=$db_name,dc=bacula,dc=com"
BINDPASS=rootroot
LDAPQUERY="dc=$db_name,dc=bacula,dc=com/(cn=%u)"

out_sed="${tmp}/sed_tmp"
cp ${conf}/bacula-dir.conf ${tmp}/bacula-dir.conf
echo "s!@BINDDN@!${BINDDN}!g" >> ${out_sed}
echo "s!@BINDPASS@!${BINDPASS}!g" >> ${out_sed}
echo "s!@LDAPQUERY@!${LDAPQUERY}!g" >> ${out_sed}

sed -i -f ${out_sed} ${tmp}/bacula-dir.conf
mv ${tmp}/bacula-dir.conf ${conf}/bacula-dir.conf
rm ${out_sed}

start_test

# export debug=1

cat << END_OF_DATA >${tmp}/bconcmds
@output /dev/null
messages
@$out ${tmp}/log.out
status dir
setdebug dir level=500 trace=1
quit
END_OF_DATA

run_bacula

# now check if we have ldap-dir loaded
if [ "$(grep -c ldap-dir ${tmp}/log.out)" -lt 1 ]
then
   echo "BPAM LDAP Plugin is not loaded, cannot perform the test!"
   exit 1
fi

# now we should test authentication
printf "Authentication test ... "
estat=0

# check invalid login
printf "admin\nadmin\nstatus dir\nquit\n" | ${bin}/bconsole -p -C ldaptest -c bconsole.auth-ldap-plugin.conf > ${tmp}/log1.out 2>&1
if [ "$(grep -c Version: ${tmp}/log1.out)" -gt 0 ]
then
   printf "failed ... "
   estat=1
else
   if [ "$(grep -c "LDAP Authentication Successfull" ${working}/*.trace)" -gt 0 ]
   then
      estat=2
   fi
fi

# check proper login
printf "root\nrootroot\nstatus dir\nquit\n" | ${bin}/bconsole -p -C ldaptest -c bconsole.auth-ldap-plugin.conf > ${tmp}/log2.out 2>&1
if [ "$(grep -c Version: ${tmp}/log2.out)" -lt 1 ]
then
   printf "failed ... "
   estat=3
else
   if [ "$(grep -c "LDAP Authentication Successfull" ${working}/*.trace)" -lt 1 ]
   then
      estat=4
   fi
fi

echo "done"

cat << END_OF_DATA >${tmp}/bconcmds
status dir
quit
END_OF_DATA

run_bconsole

export CHECK_JOBMEDIA=0
export CHECK_OPENFILE=0
stop_bacula
stop_local_slapd
end_test
