#!/bin/sh
# yp.pwupdate	- update NIS passwd maps.
#		  (C) 1994 Olaf Kirch, <okir@monad.swb.de>
#		  This software is covered by the GNU GPL.
#
# This script updates the passwd.* maps for all domains served
# by this host. We make a feeble attempt at locking, so as to
# avoid concurrent builds on the databases. However, this locking
# does _not_ guard us against the NIS maintainer running make while
# we build our maps. Maybe it's time for a ypmake tool...

# This script tries to be clever in guessing whether shadow passwords
# are used or not. Patches by Charles Lopez, tjarls@infm.ulst.ac.uk.
test -f /etc/shadow
have_shadow=$?

tmp=/tmp/ypwd.upd.$$
lock=/tmp/yppasswd.lock

mailinfo ()
{
    if [ -x /usr/bin/mailx ]; then
        mailx -s "$1" $2
    else
        sendmail $2
    fi
}

echo $$ > $tmp
i=0;
while ! ln $tmp $lock; do
    sleep 10;
    i=`expr $i + 1`;
    if [ $i -gt 60 ]; then
        echo "NIS passwd maps seem permanently locked" |
            mailinfo "Could not remake NIS passwd.* maps" root
        exit 2
    fi
done

mtemp=/tmp/ypw.tmp.$$
merr=/tmp/ypw.err.$$

if [ $have_shadow -eq 0 ]; then
    cd /etc; 
    if ! pwunconv > $mtemp 2>&1; then
    	(
    	echo "Couldn't pwunconv your /etc/shadow file."
    	echo "Error messages:"
    	cat $mtemp
    	echo
    	) | mailinfo "Could not remake NIS passwd.* maps" root
        exit 2
    fi
fi

cd /var/yp
for dir in *; do
    if [ -d $dir -a "$dir" != "binding" ]; then
	(
	    cd $dir && 
	    (
	        if [ -f "$dir/Makefile" ]; then
	            makefile="$dir/Makefile"
	          else
	            makefile="../Makefile"
	        fi
	        if ! make -sk -f $makefile passwd > $mtemp 2>&1; then
		    echo "Errors in $PWD:"
		    cat $mtemp
		    echo
	        fi >> $merr
	    )
	)
    fi
done
# rm -f /etc/npasswd

if [ -s $merr ]; then
    (
    echo "The following errors occurred while remaking the NIS passwd maps"
    echo
    cat $merr
    ) | mailinfo "Errors while remaking NIS passwd.* maps" root
fi
rm -f $mtemp $merr

rm -f $tmp $lock
