#!/bin/bash 
# $Id: ldap-add-user-to-group 67719 2010-08-03 19:54:05Z pere $
# This script takes 2 parameters.
# The host name and the netgroup to add the host into.  Use at own
# risk

HOST=$1
NETGROUP=$2

if [ -z "$HOST" -o -z "$NETGROUP" ] ; then 
  echo -e "Usage:\t$0 <hostname> <netgroup>"
  echo
  echo "  Adds a host as a member in the given netgroup."
  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=$NETGROUP)(objectClass=nisNetgroup))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')
if [ "$groupdn" ] ; then
    echo "LDAP bind as $admindn"
    cat << EOF | ldapmodify -ZZ -D "$admindn" -W -v -x
dn: $groupdn
changetype: modify
add: nisNetgroupTriple
nisNetgroupTriple: ($HOST,-,)
EOF
else
    echo "error: unable to find group"
fi
