#!/bin/sh

set -e

cd $(dirname $0)

. ../../common/config.sh
. ../../common/log.sh

log_start "$0" "Change an user's password with chpasswd"

save_config

# restore the files on exit
trap 'log_status "$0" "FAILURE"; restore_config' 0

change_config

echo -n "Change user nobody's password (echo nobody:test | chpasswd)..."
echo nobody:test | chpasswd
echo "OK"

echo -n "Check the passwd file..."
../../common/compare_file.pl config/etc/passwd /etc/passwd
echo "OK"
echo -n "Check the group file..."
../../common/compare_file.pl config/etc/group /etc/group
echo "OK"
echo -n "Check the shadow file..."
../../common/compare_file.pl 01_chpasswd/shadow /etc/shadow
echo "OK"
echo -n "Check the number of rounds..."
rounds1=$(sed -n 's/^nobody:\$5\$rounds=\([0-9]*\)\$.*$/\1/p' /etc/shadow)
echo -n "($rounds1)..."
if [ "$rounds1" -lt 3000 ] || [ "$rounds1" -gt 10000 ]; then
	echo "Wrong rounds: $rounds1"
	grep "^nobody:" /etc/shadow
	exit 1
fi
echo "OK"
echo -n "Check the gshadow file..."
../../common/compare_file.pl config/etc/gshadow /etc/gshadow
echo "OK"

echo ""
echo "Make sure the number of rounds is not constant"

echo -n "  Change user nobody's password (echo nobody:test | chpasswd)..."
echo nobody:test | chpasswd
echo "OK"

rounds2=$(sed -n 's/^nobody:\$5\$rounds=\([0-9]*\)\$.*$/\1/p' /etc/shadow)
if [ "$rounds1" = "$rounds2" ]; then
	echo "The number of rounds did not change."
	echo "It may not be a error, please re-run this test."
	exit 1
fi
echo -n "($rounds2)..."
echo "OK"

log_status "$0" "SUCCESS"
restore_config
trap '' 0

