#!/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-}" "<section> <groupname> [<user> [..]]" <<EOF
  Adds extra group
EOF
}

# get_free_gid <retvar> <searchbase> <searchlimit>
function get_free_gid() {
    (( $# == 2 )) || (( $# == 3 )) || \
        bb_fatal "get_free_gid needs 2 or 3 args but called with $#"

    local _gid=$2
    local -i _limit="${3-0}"

    while ldap_cmd read ldapsearch \
        "(&(objectClass=posixGroup)(gidNumber=$_gid))" \
        gidNumber | grep -E -q '^gidNumber:'
    do
        (( _gid <= _limit )) || {
            bb_msg err "gid limit hit"
            return 1
        }
        _gid=$((_gid + 1))
    done
    printf -v "$1" "%i" "$_gid"
}

# config_read_groupadd <section>
function config_read_groupadd() {
    (( $# == 1 )) || \
        bb_fatal "config_read_groupadd: called with $# instead of 1 arg"

    local _section="$1"

    # values for selected section
    config_read_mandatory GID_BASE "group base" "$_section"
    # shellcheck disable=SC2034
    config_read GID_LIMIT "group limit" "$_section" || GID_LIMIT=0
}

function main() {
    (( $# > 1 )) || local_usage 1 "missing arguments"

    local _section="$1"
#    local _group_name="$2"
    shift 2

    config_init
    config_read_groupadd "$_section"

    local _gid
    bb_fatal "IMPLEMENT ME and remove section as local arg!"
}

parse_common_args main "" "" "$@"
bb_quit
