#!/bin/csh -f

# This script recursively expands a netgroup from NIS.

set YPWHICH = `which ypwhich`
if ($status) goto tryipa
ypmatch $1 netgroup |& grep -v "Local domain name not set" > /dev/null
set FOO = `ypmatch $1 netgroup |& egrep -v "Local domain name not set|Can't match key"`
if ($status) goto tryipa
if ($status) exit
foreach BAR($FOO)
	echo "$BAR" | grep "(" > /dev/null
#	echo $status
	if ($status) then
		$0 $BAR
	else
		echo $BAR
	endif
end

exit

tryipa:

set IPA = `which ipa`
if ($status) exec ypmatch $1 netgroup
set TMP = /tmp/`basename $0`.$$

/bin/ipa netgroup-show $1 |& sed 's;^ *;;' > $TMP
# If ipa is broken or we don't know about this netgroup, quit right here
set STATUS = $status
if ($STATUS) exit $STATUS
grep ERROR $TMP > /dev/null
if (! $status) then
    set DQ = '"'
    echo ${DQ}/bin/ipa netgroup-show $1$DQ produced an error -- see $TMP
    exit 1234
endif

set NETGROUPLINES = "^Member netgroups:"
set NETGROUPS = `egrep "$NETGROUPLINES" $TMP | sed -e 's;.*:;;' -e 's;,;;g'`
#echo $1 "=>" $NETGROUPS
foreach NETGROUP ( $NETGROUPS )
    $0 $NETGROUP
end
egrep -v "$NETGROUPLINES" $TMP > $TMP.new
mv $TMP{.new,}

set HOSTLINES = "^External host:|^Member Host:"
set HOSTS = `egrep "$HOSTLINES" $TMP | sed -e 's;.*:;;' -e 's;,;;g'`
#echo $1 "=>" $HOSTS
foreach HOST ( $HOSTS )
    echo $HOST
end
egrep -v "$HOSTLINES" $TMP > $TMP.new
mv $TMP{.new,}

set JUNKLINES = "^Netgroup name:|^Member of netgroups:|^Indirect Member netgroups:|^NIS domain name:|^Description:|^Member User:|^Host category:|^Member Hostgroup:"
egrep -v "$JUNKLINES" $TMP > $TMP.new
mv $TMP{.new,}


if (! -z $TMP) then
    echo ${0}: Unrecognized output from \"/bin/ipa netgroup-show $1\:
    sed 's;.;  &;' $TMP
endif
/bin/rm -f $TMP
