#!/bin/sh
# cleangroup.sh created 20050823 jamey hopkins
# sort /etc/group by group id, sort users in group, and remove users not in /etc/passwd
#
# History:
# ------------------------------------------------------------------
# 20050823 jah - new


>group.new

cat /etc/group | sort -k3 -t: -n > group.$$
while read LINE
do
	GNAME=`echo $LINE | cut -f1 -d:`
	GPASS=`echo $LINE | cut -f2 -d:`
	GGRID=`echo $LINE | cut -f3 -d:`
	GUSER=`echo $LINE | cut -f4 -d:`
	echo "Processing -> $GNAME";
	# strip out commas and sort
	NGUSER=`echo $GUSER | tr , '\n' | sort | uniq`
	# build userlist
	>userlist.$$
	for x in `echo $NGUSER`
	do
		echo $x >>userlist.$$
	done
	# remove non existant users
	>userlist.new.$$
	while read ULINE
	do 
		grep ^$ULINE: /etc/passwd >/dev/null 2>&1
		if [ "$?" = "0" ] 
		then
			echo $ULINE>>userlist.new.$$
		else
			echo "Removing $ULINE"
		fi
	done<userlist.$$
	GUSER=`cat userlist.new.$$`
	GUSER=`echo $GUSER | sed 's/ /,/g'`
	echo $GNAME:$GPASS:$GGRID:$GUSER >>group.new
done<group.$$

rm group.$$ userlist.$$ userlist.new.$$ >/dev/null 2>&1

echo
echo "New group created as group.new. Verify integrity and cat group.new >/etc/group if good."
echo