#!/bin/bash
#
# Resets the LDAP admin@domain.com password for Core

. /etc/federated
. /federated/lib/functions.sh

usage() {
cat << EOF
Reset the LDAP admin@domain.com password
Usage: $0 password
Arguments:
                    password - the password to set the admin@domain.com account to

EOF
exit 2;
}

[ $# -ne 1 ] && usage
PASSWORD=$1

get_ldapdomain
[ ! -d "/federated/apps/ldap" ] && echo "* ldap is not installed." && exit 2
LDAP_BIND_PASSWORD=$(cat /federated/apps/ldap/.ldap.secret)

if [[ $LDAP_DOMAIN_MIDDLE ]]; then
  # Check if admin user exists first
  [[ ! $(docker exec ldap ldapsearch -x -LLL -H ldap://localhost -b dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_MIDDLE,dc=$LDAP_DOMAIN_LAST -w $LDAP_BIND_PASSWORD -D cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_MIDDLE,dc=$LDAP_DOMAIN_LAST uid=admin) ]] && echo "* admin user doesn't exist." && exit 2

  echo -ne "* Resetting the LDAP admin@$LDAP_DOMAIN_FIRST.$LDAP_DOMAIN_MIDDLE.$LDAP_DOMAIN_LAST password.."
  docker exec ldap ldappasswd -H ldap://localhost -D "cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_MIDDLE,dc=$LDAP_DOMAIN_LAST" -x -w $LDAP_BIND_PASSWORD -s $PASSWORD uid=admin,ou=people,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_MIDDLE,dc=$LDAP_DOMAIN_LAST -Z
  [ $? -ne 0 ] && failcheck "* Couldn't run ldappasswd inside ldap container"
  echo -ne "done.\n"
else
  # Check if admin user exists first
  [[ ! $(docker exec ldap ldapsearch -x -LLL -H ldap://localhost -b dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST -w $LDAP_BIND_PASSWORD -D cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST uid=admin) ]] && echo "* admin user doesn't exist." && exit 2

  echo -ne "* Resetting the LDAP admin@$LDAP_DOMAIN_FIRST.$LDAP_DOMAIN_LAST password.."
  docker exec ldap ldappasswd -H ldap://localhost -D "cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST" -x -w $LDAP_BIND_PASSWORD -s $PASSWORD uid=admin,ou=people,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST -Z
  [ $? -ne 0 ] && failcheck "* Couldn't run ldappasswd inside ldap container"
  echo -ne "done.\n"
fi
