#!/bin/sh

set -e

cd $(dirname $0)

# Rational:
# Test the options used to provide information on the user
# (--comment, --expiredate, --shell, --inactive, --home-dir)

save()
{
	[ ! -d tmp ] && mkdir tmp
	for i in passwd group shadow gshadow
	do
		[ -f /etc/$i  ] && cp /etc/$i  tmp/$i
	done

	true
}

restore()
{
	for i in passwd group shadow gshadow
	do
		[ -f tmp/$i  ] && cp tmp/$i  /etc/$i  && rm tmp/$i
	done
	rmdir tmp
}

save

# restore the files on exit
trap 'restore' 0

cp data/{passwd,shadow,group,gshadow} /etc/

lines_passwd=$(wc -l /etc/passwd | cut -f1 -d" ")
lines_shadow=$(wc -l /etc/shadow | cut -f1 -d" ")
lines_group=$(wc -l /etc/group | cut -f1 -d" ")
lines_gshadow=$(wc -l /etc/gshadow | cut -f1 -d" ")

echo -n "Create user test3, using options..."
useradd --comment "comment test3" \
	--expiredate "2006-02-04" \
	--shell "/bin/bash" \
	--inactive "12" \
	--home-dir "/nonexistenthomedir" \
	test3
echo "OK"

echo "test if the user was added with the same uid"
echo -n "  passwd..."
getent passwd test3 |
	egrep "^test3:x:([0-9]+):\\1:comment test3:/nonexistenthomedir:/bin/bash$"
echo "  OK"
uid=$(getent passwd test3|sed -ne "s/test3:x:\([0-9]*\):.*/\\1/p")
# uid must be greater than UID_MIN (in login.defs)
echo -n "  uid: $uid < 1000..."
test $uid -ge 1000
echo -n "  group..."
getent group test3  | egrep "^test3:x:$uid:$"
echo "  OK"
echo -n "  shadow..."
getent shadow test3 | egrep "^test3:!:[0-9]+:0:99999:7:12:13183:$"
echo "  OK"
echo -n "  gshadow..."
egrep "^test3:!::$" /etc/gshadow
echo "  OK"
# the home directory should not exist
echo -n "  no homedir..."
test -d /home/test3 && exit 1 || true
echo "  OK"
echo -n "  number of lines"
test $(( lines_passwd  + 1 )) = $(wc -l /etc/passwd | cut -f1 -d" ")
echo -n "."
test $(( lines_group   + 1 )) = $(wc -l /etc/group | cut -f1 -d" ")
echo -n "."
test $(( lines_shadow  + 1 )) = $(wc -l /etc/shadow | cut -f1 -d" ")
echo -n "."
test $(( lines_gshadow + 1 )) = $(wc -l /etc/gshadow | cut -f1 -d" ")
echo -n "."
echo "  OK"

echo -n "delete this user..."
userdel test3
echo "OK"

echo "check if the user was deleted"
echo -n "  no entries..."
egrep "^test3:" \
      /etc/passwd /etc/group /etc/shadow /etc/gshadow && exit 1 || true
echo "  OK"
echo -n "  no homedir..."
test -d /home/test3 && exit 1 || true
echo "  OK"
echo -n "  number of lines"
test $lines_passwd  = $(wc -l /etc/passwd | cut -f1 -d" ")
echo -n "."
test $lines_group   = $(wc -l /etc/group | cut -f1 -d" ")
echo -n "."
test $lines_shadow  = $(wc -l /etc/shadow | cut -f1 -d" ")
echo -n "."
test $lines_gshadow = $(wc -l /etc/gshadow | cut -f1 -d" ")
echo -n "."
echo "  OK"

