#!/bin/bash
# UpdateClients.sh
# 

usage () {
    echo Usage: `basename $0` "[--help] [--list] [--disable] [--room <room>] [--script <script>]"
	echo "       --help    = this message"
	echo "       --list    = list available rooms"
	echo "       --disable = disable update"
	echo "       --room    = enter room name here"
	echo "       --script  = enter user-defined scriptname"
    exit 0
}

rooms () {
    echo "Available rooms:"
    ldapsearch -x "(&(Objectclass=SchoolRoom)(description=*))" description |  awk '/description:/ {print $2}'
    exit 0
}

export TMPDIR=`mktemp -d /var/tmp/UpdateClients-XXXXXX`
UPDATE_ROOMS=""
UPDATE_SCRIPT="online-update.sh"

if test x-h = "x$1" -o x--help = "x$1"; then
    usage
fi

while test -n "$1"; do
	PARAM="$1"
	ARG="$2"
	shift
	case $PARAM in
	-r|--room)
	KNOWN_ROOMS=`ldapsearch -x "(&(Objectclass=SchoolRoom)(description=*))" description |  awk '/description:/ {print $2}'`;
	for i in $KNOWN_ROOMS; do
		if [ "$ARG" == "$i" ]; then
			UPDATE_ROOMS="$i"
		fi
	done
	if [ "$UPDATE_ROOMS" == "" ]; then
		echo "No room $ARG - exiting..."
		exit 1
	fi
	shift
	;;
	-d|--disable)
	DISABLE_UPDATE=true
	;;
	-s|--script)
	UPDATE_SCRIPT="$ARG"
	shift
	;;
	-h|--help)
	usage
	;;
	-l|--list)
	rooms
	;;
	-*)
	echo "Unknown option $PARAM"
	usage
	;;
	esac
done

# update each client in $UPDATE_ROOMS

if [ "$UPDATE_ROOMS" == "" ]; then
 UPDATE_ROOMS=`ldapsearch -x "(&(Objectclass=SchoolRoom)(description=*))" description |  awk '/description:/ {print $2}'`
fi

if [ $DISABLE_UPDATE ]; then
 for ROOM in  $UPDATE_ROOMS; do
  for PC in `ldapsearch -x "(&(objectClass=SchoolWorkstation)(sn=$ROOM*Workstation-User))" dn | grep dn  | cut -d " " -f 2 | grep -v requesting`; do
  /bin/cat >> $TMPDIR/$PC.ldiff << EOF_LDIF
dn: $PC
changetype: modify
replace: clientMustUpdate
clientMustUpdate: no

EOF_LDIF
 done
done

else

for ROOM in $UPDATE_ROOMS; do
 for PC in `ldapsearch -x "(&(objectClass=SchoolWorkstation)(sn=$ROOM*Workstation-User))" dn | grep dn  | cut -d " " -f 2 | grep -v requesting`; do
  /bin/cat >> $TMPDIR/$PC.ldiff << EOF_LDIF
dn: $PC
changetype: modify
replace: clientUpdatePath
clientUpdatePath: $UPDATE_SCRIPT
-

dn: $PC
changetype: modify
replace: clientMustUpdate
clientMustUpdate: yes

EOF_LDIF
 done
done

fi

for i in $TMPDIR/*; do
 PASS=`/usr/sbin/get_admin_pw`
 DN=`cat /etc/openldap/slapd.conf | grep -v "#" | awk '/rootdn/ {print $2}' | cut -d "\"" -f 2`
 ldapmodify -x -D $DN -w $PASS -f $i 1>/dev/null
done

rm -rf $TMPDIR
exit 0

