#!/bin/sh

# Copyright (C) 2025-2026 Daniel Baumann <daniel@debian.org>
#
# SPDX-License-Identifier: GPL-3.0+
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -e

PROGRAM="$(basename ${0})"
SOFTWARE="bfh-ssp"

# Parameter
PARAMETER="${1}"

if [ -z "${PARAMETER}" ]
then
	echo "Usage: ${PROGRAM} {tel|uid|uidNumber|cn|...} STRING" >&2
	echo
	echo "Examples:"
	echo "  User:  ${0} uid bad9"
	echo "  Phone: ${0} tel 84822"
	echo "  Group: ${0} cn IDM.infra.linux.sysadmin"
	echo "  All groups: ${0} cn 'IDM.*'"
	echo
	echo "See ${PROGRAM}(1) and ${SOFTWARE}(7) for more information."

	exit 1
fi

LDAP_SERVER="ldaps://ldap.bfh.info:636"

LDAPSEARCH_OPTIONS="-LLL -o ldif_wrap=no"

LDAP_BASE="dc=bfh"

LDAP_BIND_DN=""

# Run
ACTION="${1}"
ARGUMENT="${2}"

if [ -z "$ARGUMENT" ]
then
	ldapsearch ${LDAPSEARCH_OPTIONS} -H ${LDAP_SERVER} -x ${LDAP_BIND_DN} -b ${LDAP_BASE} -s sub ${ACTION}
else
	case "${ACTION}" in
		tel)
			ldapsearch ${LDAPSEARCH_OPTIONS} -H ${LDAP_SERVER} -x ${LDAP_BIND_DN} -b ${LDAP_BASE} -s sub telephoneNumber=*${ARGUMENT} | grep --color=never -E '^(cn|displayName|telephoneNumber): '
			;;
		*)
			ldapsearch ${LDAPSEARCH_OPTIONS} -H ${LDAP_SERVER} -x ${LDAP_BIND_DN} -b ${LDAP_BASE} -s sub ${ACTION}=${ARGUMENT}
			;;
	esac
fi
