#!/bin/bash

###############  Arguments  ###############

usage() {
	cat <<-EOF
		This script removes NIS/LDAP user (entry prefixed with +) from
		/etc/passwd, removes her from all supplementary groups and optionally
		trashes her home.

		Usage: ${scriptname} [options] LOGIN

		Options:
		-r, --remove               remove home directory.
		-h, --help                 show this help.
	EOF
}

scriptname=$(basename $0)
delhome=

while [ $# -gt 0 ]; do
	case $1
	in
		-r | --remove)
			delhome='delhome'
			shift
	;;
		-h | --help)
			usage
			exit 0
	;;
		-*)
			echo "${scriptname}: Unknown option $1" >&2
			echo; usage
			exit 1
	;;
		*)
			user=$1
			break
	;;
	esac
done


if [ -z "$user" ]; then
	echo "${scriptname}: Missing LOGIN" >&2
	echo; usage
	exit 1
fi


###############  Main  ###############

fail() {
	echo "$1" >&2
	exit 2
}

if ! grep "^+${user}:" /etc/passwd &>/dev/null; then
	fail "User ${user} is not defined in /etc/passwd or is not a NIS user."
fi

if [ -n "$delhome" ]; then
	home="$(getent passwd ${user} | cut -d: -f6)"

	for p in '' '/' '/dev/null'; do
		if [ "$home" == "$p" ]; then
			fail "User's home is '${home}'; you really SHOULD NOT delete this..."
		fi
	done

	read -p "Are you sure want to delete ${home} ? Type 'yes' to continue: " answer
	if [ "$answer" == 'yes' ]; then
		rm -Rfv -- "$home"
	else
		fail "Aborted."
	fi
fi

# remove user from all supplementary groups
usermod -G '' "$user"

# remove user form passwd
sed -i "/+${user}:/d" /etc/passwd