#!/bin/csh -f
#
#  rmuser  - remove users, in the same vein as adduser.
#  	     leaves phonelist entry for future reference.
#
# 	   -a flag makes it actually remove from the passwd file
#	   default is to replace password with the date, and leave 
#	   /etc/passwd.   This allows accounting to correctly 
#	   identify the user at the end of the month.
#
# get user if not on cmd line.
#
onintr quit:

set absolute=0
if (${#argv} < 1)  then
	echo "enter user to be removed."
	set argv=$<
endif
#
if ( $1 == "-a" ) then
	set absolute=1
	set argv[1]=
	echo "removing absolutely\!"
endif
#
#
#  initialize files to be altered.
#
set group="/etc/group"
set passwd="/etc/passwd"
set maildir="/usr/spool/mail"
#
umask 220
set datenow = `date`
set month = $datenow[2]
set year = $datenow[6]
@ yearsuffix = $year - 1900
set date = $month$yearsuffix
set null
#
#  run login loop, rm'ing each.
#
foreach login ($argv)
	set good=`grep "^${login}:" ${passwd} | awk -F: '{print $5}'`
	if ("${good}" == "${null}") then
		set msg=" not in password file."
		echo ${login} ${msg}
		continue
	endif
#
#  verify removal of this user.
#
	if (${login} == "root") then
		echo "no removing root allowed\!"
		echo "you will have to do it the hard way."
		continue
	endif
#
	echo "ok to remove ${good}? (y/n)"
		set ans=$<
	if (${ans} != y) continue
#
#  find home directory in passwd file
#
	set home=`grep "^${login}:" ${passwd} | awk -F: '{print $6}'`

	echo ${home}
	echo "ok to remove home?(${home}) (y/n)"
	set ans=$<
	if (${ans} != y) then
		echo "continue with removing this user? (y/n)"
		set ans=$<
		if (${ans} != y) continue
	else
		echo "removing home"
		rm -r ${home}
	endif
#
#  remove mail
#
	echo "removing mail"
	set mail="${maildir}/${login}"
	if (-e ${mail}) rm -f ${mail}
#
#  remove passwd entry.
#
	while (-e /etc/ptmp)
		echo "Waiting for password file to become available."
		sleep 5
	end
	touch /etc/ptmp
	echo "removing passwd entry"
	if ($absolute) then
		echo "/"^$login":[^:]*:/d" > /tmp/rmu$$
	else
		echo "s/^"$login":[^:]*:/"$login":"$date":/" > /tmp/rmu$$
	endif
	sed -f /tmp/rmu$$ ${passwd} > /etc/ptmp
	mv /etc/ptmp ${passwd}
#
#  remove login name from group file
#
	echo "removing group entry"
	set scrpt="g/,${login},/s//,/"
	echo ${scrpt} > /tmp/rmu$$
	set scrpt="g/,${login}/s///"
	echo ${scrpt} >> /tmp/rmu$$
	set scrpt="g/:${login},/s//:/"
	echo ${scrpt} >> /tmp/rmu$$
	set scrpt="w"
	echo ${scrpt} >> /tmp/rmu$$
	set scrpt="q"
	echo ${scrpt} >> /tmp/rmu$$
	ed ${group} </tmp/rmu$$
#
#  wrap up and continue.
#
	rm /tmp/rmu$$
end  #foreach

quit:
	rm -f /tmp/rmu$$
