#!/bin/sh

set -e

cd $(dirname $0)

# Rational:
# Test that useradd do not accept UID that will cause overflow

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 test1 with UID 2147483648..."
msg=$(useradd -u 2147483648 test1 2>&1) && exit 1 || test "$?" = "3"
test "$msg" = "useradd: invalid numeric argument '2147483648'"
echo "OK"

echo "check that the user was not added"
echo -n "  passwd..."
getent passwd test1 && exit 1 || true
echo "  OK"
echo -n "  group..."
getent group test1 && exit 1 || true
echo "  OK"
echo -n "  shadow..."
getent shadow test1 && exit 1 || true
echo "  OK"
echo -n "  gshadow..."
egrep "^test1:!::$" /etc/gshadow && exit 1 || true
echo "  OK"
# the home directory should not exist
echo -n "  no homedir..."
test -d /home/test1 && 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"

