#!/bin/bash

usage() {
	echo Given an OLD savefile from a prior run of this program,
	echo will run a new ypcat -k netgroup, and then generate three files:
	echo "  0. The current netgroup output in correct format"
	echo "  1. A list of entries needing deletion"
	echo "  2. LDIF output for adds and modifications."
	echo ""
	echo "NOTE::::::"
	echo This means you need to save the netgroup file generated
	echo from the last time you ran this program '!!!!!!'
	echo ""
	exit 1
}

if ! test -f "$1" ; then usage ; fi

if grep 'netgroup,v ' $1; then
	echo ERROR: DO NOT CALL THIS ON A COPY OF /usr/lsd/conf/netgroup
	echo ERROR: MUST BE from ypcat -k netgroup ONLY
	exit 1
fi

if ! test -x migrate_netgroup.pl ; then
	echo ERROR: must run this in the MigrationTools directory
	exit 1
fi

# Because netgroup format is buggy about comments
# (and so ypcat -k can leave comments in)

#############################################################
# The algorithms below rely on an expected format of
#  [alphanumeric KEY string] [SPACE] [Alphanumeric VALUE string follows]
#

oldfile=/tmp/update.netgroup.old
newfile=/tmp/update.netgroup.new
modfile=/tmp/update.netgroup.ldif
delfile=/tmp/update.netgroup.del

rm $oldfile $newfile $modfile 2>/dev/null

sed '/^#/d' $1 |sort -u > $oldfile
ypcat -k netgroup | sed '/^#/d' $2 |sort -u > $newfile

test -s $newfile || exit 1

deletes=`comm -23 $oldfile $newfile | awk '{print $1}'`

# have to pull out the full entries after doing this
newandmodified=`comm -13 $oldfile $newfile`

# in theory would like to generate script around ldapdelete,
# but that requires DN and password handling
for n in $deletes ; do
	echo $n
done > $delfile

for n in $newandmodified ; do
	grep '^'$n' ' $newfile 
done > ${modfile}.txt

./migrate_netgroup.pl ${modfile}.txt $modfile

echo delete list is in $delfile
echo mod LDIF is in $modfile
echo and DONT FORGET TO SAVE $newfile



