#!/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() {
    (( $# < 3 )) || \
        bb_fatal "local_usage called with $# instead of 1 or 2 args"
    usage "${1-1}" "${2-}" "<user-cn> [..]" <<EOF
  User information lookup program like traditional finger, but queries ldap.
  Returns 1 if any user is not found, 0 otherwise.
EOF
}

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

    local _user_cn="$1"
    ldap_cmd read ldapsearch \
        "uid=$_user_cn" uid uidNumber homeDirectory loginShell gecos | \
        awk --assign verbosity="${VERBOSITY}" \
        '/^uid: '"$_user_cn"'$/ {found=1; uid=$2} /^loginShell: / {loginshell=$2} /^gecos: / {gsub("gecos: ","");gecos=$0} /^uidNumber: / {uidnumber=$2} /^homeDirectory: / {homedir=$2} END { if (found) { if( verbosity > 1 ) printf "CN/Login: %s\nUID: %s\nGecos: %s\nShell: %s\nHomedir: %s\n", uid, uidnumber, gecos,loginshell,homedir } else exit 1}' || return 1

    local finger__user_homedir
    if ldap_resolve_user_homedir finger__user_homedir "$_user_cn"
    then
        (( VERBOSITY < 2 )) || \
            echo "Homedir is autofs based, real homedir: $finger__user_homedir"
    else
        (( VERBOSITY < 2 )) || echo "Homedir is not autofs based."
    fi
}

function main() {
    # shellcheck disable=SC2119
    (( $# > 0 )) || local_usage 1 "Missing mandatory argument"

    config_init

    local _retval=0

    while (( $# > 0 ))
    do
        finger "$1" || {
            bb_msg info "no such user: $1"
            _retval=1
        }
        shift
        (( $# == 0 )) || echo
    done

    bb_quit "$_retval"
}

parse_common_args main "" "" "$@"
bb_fatal "reached unreachable code"
