#!/bin/bash
# $Id$
# This tools take 2 parameters
# User name and the location of the new home directory
# use at own risk


UNAME=$1
NEWHOME=$2

if [ -z "$UNAME" -o -z "$NEWHOME" ] ; then 
  echo "usage:\n\t$0 <username> <newhome>"
  exit 9
fi

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

USERDN=$(ldapsearch -x "(&(uid=$UNAME)(objectClass=posixAccount))" 2>/dev/null | perl -p0e 's/\n //g' | awk '/^dn: / {print $2}')

OLDHOME=$(getent passwd $1| cut -f6 -d:)

if [ -z "$OLDHOME" -o ! -d "$OLDHOME" -o ! -d "$NEWHOME" ] ; then 
  echo "please make sure thet $UNAME have a home, and that $NEWHOME exists"
  exit 9
fi

if [ -d "$NEWHOME/$UNAME" ] ; then 
  echo "sorry, $NEWHOME/$UNAME already exists"
  exit 9
fi


mv "$OLDHOME" "$NEWHOME"

cat <<EOF | ldapmodify -ZZ -D "$ADMIN" -W -v -x
dn: $USERDN
changetype: modify
replace: homeDirectory
homeDirectory: $NEWHOME/$UNAME
EOF

(
  cd $NEWHOME/$UNAME
  grep -rl "$OLDHOME" .openoffice .sversionrc Desktop .kde* 2>/dev/null | \
    while read FILE ; do echo -e ",s:$OLDHOME:$NEWHOME/$UNAME:g\nwq" | ed "$FILE" ; done 
)
