#!/usr/bin/env bash

# {{ ansible_managed }}

# Lookup SSH public key in LDAP

# shellcheck disable=SC2034
username="${1}"

# shellcheck disable=SC2034
service="sshd"

# shellcheck disable=SC2034
hostname="$(hostname)"

# shellcheck disable=SC2034
domain="$(dnsdomainname)"

# shellcheck disable=SC2034
fqdn="$(hostname --fqdn)"

ldap_binddn="{{ sshd__ldap_binddn }}"
ldap_bindpw="{{ sshd__ldap_bind_pw_file }}"

ldap_filter="{{ sshd__ldap_filter }}"

ATTRIBUTE=$(ldapsearch -Z -LLL -x -y "${ldap_bindpw}" -D "${ldap_binddn}" -o ldif-wrap=no -S sshPublicKey "${ldap_filter}" sshPublicKey | grep -v 'dn:')

if [[ $ATTRIBUTE == sshPublicKey::* ]];
then
  KEY=$(echo "$ATTRIBUTE" | perl -pe 's/sshPublicKey:: //;' | base64 -d)
else
  KEY=$(echo "$ATTRIBUTE" | perl -pe 's/sshPublicKey: //;')
fi

if [ -n "${KEY}" ] ; then
  echo "${KEY}"
fi
