#!/bin/sh
# Orginal script -> http://nicolas.barcet.com/drupal/mmldap

URI="ldap://server1.example.com"
BASEDN="ou=example.com,dc=example,dc=com"
GROUPBASE="ou=Groups,ou=example.com,dc=example,dc=com"
BINDDN="cn=admin,dc=example,dc=com"
PASS=howtoforge

if (test -n "$2") then
        GROUP=$1
        LISTNAME=$2
        if (test -n "$3") then
                OPTIONS=$3
        else
                OPTIONS="-a=no -d=no -w=no -g=no"
        fi

        echo "$0 invoked at `date` for list $LISTNAME (group $GROUP)"

        if (test -f "/tmp/mmlist") then
                rm /tmp/mmlist
        fi

        if (test -f "/tmp/clean_mmlist") then
                rm /tmp/clean_mmlist
        fi

        for uids in `ldapsearch -LLL -H $URI -D $BINDDN -b $GROUPBASE -w $PASS -x "cn=$GROUP" memberuid | grep  memberUid: | awk '{print $2}'`; do
                echo $uids
                echo ldapsearch -LLL -H $URI -D $BINDDN -b $GROUPBASE -w $PASS -x "cn=$GROUP" memberuid | grep  memberUid: | awk '{print $2}'
                ldapsearch -LLL -H $URI -D $BINDDN -b $BASEDN -w $PASS -x uid=$uids mail | grep mail:| awk '{print $2}' >> /tmp/mmlist
        done
        clean-email-list /tmp/mmlist > /tmp/clean_mmlist
        sync_members $OPTIONS -f /tmp/clean_mmlist $LISTNAME
        rm /tmp/mmlist /tmp/clean_mmlist
        echo "$0 finished at `date` for list $LISTNAME (group $GROUP)" 

else
        echo " Usage: $0 <ldap-group> <list-name> [<listoptions>]"
        echo "  <ldap-group> is the ldap group name"
        echo "  <listname> is the name of and existing mailman list"
        echo "  <listoptions> are the parameters passed to mailman's sync_members command"
        echo "                (defaults are : -a=no -d=no -w=no -g=no)"
fi