#!/bin/sh

set -e

cd $(dirname $0)

# Rational:
# Test useradd -g accepts textual groups

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 test4 in group nogroup..."
useradd test4 -g nogroup

echo "test if the user was added"
echo -n "  passwd..."
getent passwd test4 |
	egrep "^test4:x:([0-9]+):65534::/home/test4:/bin/sh$"
echo "  OK"
uid=$(getent passwd test4|sed -ne "s/test4: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 "  OK"
echo -n "  no group test4..."
getent group test4  | egrep "^test4:x:$uid:$" && false || true
echo "  OK"
echo -n "  test4 in group nogroup..."
egrep "^nogroup:x:65534:$" /etc/group
echo "  OK"
echo -n "  shadow..."
getent shadow test4 | egrep "^test4:!:[0-9]+:0:99999:7:::$"
echo "  OK"
echo -n "  no group test4 in gshadow..."
egrep "^test4:!::$" /etc/gshadow && false || true
echo "  OK"
echo -n "  test4 in group nogroup (in gshadow)..."
egrep "^nogroup:\*::$" /etc/gshadow
echo "  OK"
# the home directory should not exist
echo -n "  no homedir..."
test -d /home/test4 && 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       )) = $(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     )) = $(wc -l /etc/gshadow | cut -f1 -d" ")
echo -n "."
echo "  OK"

