#!/bin/bash
#
# Clean up users older than N days from the attic
# Author: Finn-Arne Johansen <faj@bzz.no>
# $Id$

# Show how this thing is used

set -e 
usage () {
  echo "
usage: $0 <NUMBER_OF_DAYS>
  where NUMBER_OF_DAYS is the limit of which to delete users
  users will be delete from the \"attic\"
  and their home directory will be removed
"
}

if [ $# -ne 1 ] ; then 
  usage
  exit 9
fi

OLDERTHAN=$(date -d -${1}days +%Y%m%d235959Z 2>/dev/null)

if [ $? -ne 0 ] ; then 
  usage 
  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}')

LDAPBASE="$(debian-edu-ldapserver -b)"

TMPFILE=/tmp/$(basename $0).$$

touch $TMPFILE
chmod 0600 $TMPFILE
chown 0:0 $TMPFILE

ldapsearch -LLL -x -b "ou=attic,$LDAPBASE" \
  "(&(uid=*)(modifyTimestamp<=$OLDERTHAN))" homeDirectory | perl -p0e 's/\n //g' > $TMPFILE

if ! grep -q "^dn:" $TMPFILE ; then 
  echo "Sorry, Nothing to delete, exiting"
else
  grep "^dn:" $TMPFILE | cut -f2 -d: | ldapdelete -ZZ -x -D "$admindn" -W
  for EACH in $(grep "^homeDirectory:" $TMPFILE | cut -f2- -d:) ; do 
    rm -rf $EACH
  done 
fi

rm -rf $TMPFILE

