#!	/bin/sh
#
#	@(#)pwpass.sh	13.2 (RC International) 91/12/27
#
#	Usage:   pwpass   or   pwpass -p
#
#	pwpass:
#	- Adds all passwords i /etc/shadow to corresponding
#	  user entries in /etc/passwd.
#	- Creates the empty file /etc/default/pwpw which signals
#	  to the passwd command that passwords should be written
#	  in both /etc/shadow and /etc/passwd.
#
#	pwpass -p:
#	- Removes all passwords from /etc/passwd by running
#	  the pwconv command.
#	- Removes the file /etc/default/pwpw.
#
#	Purpose of the pwpass command:
#	By introducing the /etc/shadow file in TX 3.1 passwords
#	are removed from /etc/passwd. This will cause trouble if
#	programs are reading DIRECTLY (i.e. not through the
#	getsp... routines) from the password file /etc/passwd.
#	Thus pwpass is a way to solve this problem (in case
#	it should occur, which should be very unlikely).

set -f

PROG="pwpass"
PASSWD="/etc/passwd"
SHADOW="/etc/shadow"
PWPWFILE="/etc/default/pwpw"
PID="$$"
PWOLD="/tmp/pw.old.$PID"
PWNEW="/tmp/pw.new.$PID"

if [ $# -ge 2 ]
then
	echo "Usage:   $PROG   or   $PROG -p"
	exit 1
fi

if [ $# -eq 1 ]
then
	case "$1" in
		-p) pwconv;
		    rm -f $PWPWFILE;
		    /etc/pwserv -r
		    exit 0;;
		*)  echo "Usage:   $PROG   or   $PROG -p";
		    exit 2;;
	esac
fi

cp $PASSWD $PWOLD

IFS=':'

cat $PWOLD |
while read NAME PWF REST
do
	SHPW=`grep "^$NAME\:" $SHADOW | cut -f2 -d':'`
	LGPW=`echo $SHPW | awk '{print length($1)}'`
	if [ "$LGPW" = "13" ]
	then
		printf '%s:%s:%s\n' "$NAME" "$SHPW" "$REST"
	else
		printf '%s:%s:%s\n' "$NAME" "$PFW" "$REST"
	fi
done > $PWNEW

if cmp -s $PASSWD $PWOLD
then
	:
else
	echo "$PASSWD has been changed while running $PROG."
	echo "Cannot proceed."
	echo "Run $PROG at a time where nobody is modifying $PASSWD."
	rm -f $PWOLD $PWNEW
	exit 3
fi

mv $PASSWD ${PASSWD}.$PID
mv $PWNEW  $PASSWD
chown bin  $PASSWD
chgrp bin  $PASSWD
chmod 444  $PASSWD
rm -f $PWOLD

touch $PWPWFILE
/etc/pwserv -r

echo "$PROG finished succesfully."
echo "$PASSWD changed to include passwords."
echo "Old password file saved in ${PASSWD}.$PID"

exit 0
