#!/bin/bash 
# $Id$
# This script takes 2 parameters
# The username and the group to add the user into
# use at own risk

UNAME=$1
GROUP=$2

if [ -z "$UNAME" -o -z "$GROUP" ] ; then 
  echo -e "usage:\n\t$0 <username> <group>"
  echo
  echo "  Adds a user as a member in the given group."
  exit 9
fi

# Locate the LDAP admin DN
admindn=$(ldapsearch -x "(&(cn=admin)(objectClass=simpleSecurityObject))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')

# Look up group DN
groupdn=$(ldapsearch -x "(&(cn=$GROUP)(objectClass=posixGroup))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')
if [ "$groupdn" ] ; then
    cat << EOF | ldapmodify -ZZ -D "$admindn" -W -v -x
dn: $groupdn
changetype: modify
add: memberUid
memberUid: $UNAME
EOF
else
    groupdn=$(ldapsearch -x "(&(cn=$GROUP)(objectClass=groupOfNames))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')
    if [ "$groupdn" ] ; then
	userdn=$(ldapsearch -x "(&(uid=$UNAME)(objectClass=posixAccount))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')
	cat << EOF | ldapmodify -ZZ -D "$admindn" -W -v -x
dn: $groupdn
changetype: modify
add: member
member: $userdn
EOF
    else
	echo "error: unable to find group"
    fi
fi
