#!/usr/bin/bash

# source bash base library
# shellcheck disable=SC1091
source /usr/libexec/bash-base.bash || {
   echo "$0: fatal error: failed to source /usr/libexec/bash-base.bash" >&2
   exit 1
}

bb_require_libs bash-ini ldapusermgmt/common

# shellcheck disable=SC2120,SC2034
function local_usage() {
    usage "${1-1}" "${2-}" "users [<subhier>]" "groups [<subhier>]" <<EOF
    -f <filter>                                               .. extra filter
  Lists users or group. Optionally limited to a subhier.
  Extra filter can be "<attr>=<value>" or a more complex LDAP filter,
  see ldapsearch(1) for more info.
EOF
}

function main() {
    # shellcheck disable=SC2119
    (( $# == 1 || $# == 2 )) || local_usage 1 "Missing mandatory arguments"

    config_init

    local _mode="$1"
    local _subhier="${2-}"

    local _base="$LDAP_SEARCH_BASE"
    local _filter

    case "$_mode" in
        users)
            _base="$LDAP_USER_SUBHIER,$_base"
            _filter="(|(objectClass=posixAccount)(objectClass=account))"
            ;;
        groups)
            _base="$LDAP_GROUP_SUBHIER,$_base"
            _filter="(objectClass=posixGroup)"
            ;;
        *) local_usage 1 "expected users or groups instead of: $_mode"
    esac

    [ -z "$_subhier" ] || _base="ou=$_subhier,$_base"

    [ -z "${EXTRA_FILTER-}" ] || \
        printf -v _filter "(&(%s)%s)" "$EXTRA_FILTER" "$_filter"

    ldap_cmd read ldapsearch -LLL -b "$_base" "$_filter" dn | \
        grep -Ev '^[[:blank:]]*$' || bb_msg info "no items to list"
}

function parse_local_arg() {
    (( $# == 1 )) || bb_fatal "parse_local_arg called with $# instead of 1 arg"

    local _op_ch="$1"

    case "$_op_ch" in
        f) declare -g EXTRA_FILTER="$OPTARG";;
        *) return 1
    esac
}

parse_common_args main "f:" parse_local_arg "$@"
bb_quit
