#!/bin/sh -e

. shell-error
. /etc/cl-user.conf

[ "$#" -eq 1 ] || fatal "more arguments required"
group="$1"; shift

[ -n "$bindpw" ] && bindpw="-w $bindpw" || bindpw="-W"

#check for name
getent group "$group" && fatal "same name already exists"

#calculate gid
gid_avail="$(getent group| cut -f3 -d: |sort -unr|head -n1)"
gid_min="${gid_min:-$(sed -rn 's,^GID_MIN[[:space:]]+([^[:space:]]+),\1,p' /etc/login.defs)}"
gid_max="${gid_max:-$(sed -rn 's,^GID_MAX[[:space:]]+([^[:space:]]+),\1,p' /etc/login.defs)}"

gid=$(( $gid_avail + 1 ))

[ "$gid" -le "$gid_max" ] || fatal "not free gid available"
[ "$gid" -lt "$gid_min" ] && gid="$gid_min"

message "using gid - $gid"

#edit ldap
ldapadd -a -D "$binddn" $bindpw -x -H "ldap://${host:-localhost}"<<EOF
dn: cn=$group,ou=Group,$base
objectClass: posixGroup
objectClass: top
cn: $group
userPassword: {crypt}x
gidNumber: $gid
EOF
