#!/bin/posix/sh
# @(#)WHAT STRING HERE
#
# This script takes three arguments: ip address and hostname ADD | DELETE
# It will add these to one or more of
# /etc/hosts
# DNS / BIND
# NIS
#
# the hostname is fully qualified with domain.
#
# if this machine is not an NIS master, but is running BIND or DNS,
# the host + ip will be added to /etc/hosts, and to the 
# correct db file in the directory specified in /etc/named.boot.
# if this machine is an NIS master for the hosts map, the name
# will be added to /etc/hosts, and make will be run in /usr/etc/yp.
# if neither of these is true, the name will simply be put in /etc/hosts.

# Notes: 
#       1) serial number is not updated in db files for bind.
#       2) all authoritative bind servers are updated.
#       3) if running bind for hosts and yp for hosts, both are updated
#       4) if not running either bind or yp, only hosts files on
#          boot-server, name-server, and file-server are updated
#

#
# exit values:
# 0 --> success
# 1 --> No action was necessary
# 2 --> improper arguments
# 3 --> This machine is not authoritative for anything
# 4 --> an error occurred trying to add
# 5 --> exists already (no action taken)
#

# debugging function
function Debug {
    echo $*  >> $LOG
}

#-------------------------------------------------------------------------------
#
#
# Start setup and checking
#
#
#-------------------------------------------------------------------------------

################################################################################
# Check to see if this host is start of authority for the domain
################################################################################
function CheckSOA {
    #
    # Check to see if its solely NIS
    #
    nslookup <<-EOF 2>&1|&
    set nosearch
EOF
    if egrep -q "Command not supported for NIS lookups" <&p
    then
	$NLECHO "protoMess  NIS box"
	nis=1
	nohosts=1
	return 1
    fi

    #
    # Check to see if its solely hosts
    #
    nslookup <<-EOF 2>&1|&
    set nosearch
EOF
    if egrep -q "Command not supported for /etc/hosts lookups" <&p
    then
	$NLECHO "protoMess  /etc/hosts box"
	hosts=1
	return 1
    fi

    #
    # Check whether this system is resolver-only sytem
    #             
    
    if [ "`ps -e | grep named | awk '{print $4 }'`" = "named" ]
    then
	    #
	    # Check to see if this is authoritative for DNS
	    #
	    nslookup <<-EOF  |&
	    server $hostname
	    set nosearch
	    set nodefname
	    set norecurse
	    set q=soa
	    $domain
	EOF

	    if egrep "Non-authoritative|Authoritative answers can be" <&p  >/dev/null
	    then

		return 0
	   else
		soa=1
		return 1
	   fi
     else
          #
          # named is not running. Probably resolver-only configuration.
          #

          return 1
     fi   
     
}

################################################################################
# Check the method to use. sets one (or more) of dns, nis, hosts to 1
################################################################################
function CheckMethod {
    
    #
    # if this is a resolver-Only system then namedboot file probably won't exist
    # or is not being used.
    #


    cat << SEOF > /tmp/awkdbd.$$
    BEGIN { found=0 }
    {
	if (\$1 == "primary" && \$2 == "$domain") {
	    found = 1
	}
    }
    END { if (found)
	    printf "1"
	  else
	    printf "0"
	}
SEOF

    if [ "`ps -e | grep named | awk '{print $4 }'`" = "named" ]
    then
	    dnso=`awk < $namedboot -f /tmp/awkdbd.$$`
	    rm -f /tmp/awkdbd.$$
	    $NLECHO "protoMess  dnso = $dnso"
    else
        dnso="0"
	$NLECHO "protoMess  resolver-only system (named is not running on this host)"
    fi
   

    # may have found earlier in nslookup
    # /etc/hosts is mutually exclusive of NIS/DNS
    if [ "$hosts" != "1" ]
    then
	ypmaster=`ypwhich -m hosts.byname`
	if [ $? = 0 ]
	then
	    if [ $ypmaster = $hostname ]
	    then
		$NLECHO "protoMess  nis master"
		nis=1
	    fi
	fi
	
	if [ "$dnso" = "1" ]
	then
	    if [ "$soa" = "1" ]
	    then
		dns=1
	    fi
	fi

	if [ "$nis$dns" = "00" ]
	then
	    if [ "$nohosts" != "1" ]
	    then
		hosts=1
	    fi
	fi
    fi
}


################################################################################
# must find if there is a file for this ip ($1) in this dir
################################################################################
function CheckForDBFile {
    # if ip is 1.2.3.4 -->
    # first look for db.1.2.3.4
    # then db.1.2.3
    # then db.1.2
    # then db.1
    ip=$1
    ip1=`/bin/echo $ip | sed 's?\.[0-9]*$??'`
    ip2=`/bin/echo $ip1 | sed 's?\.[0-9]*$??'`
    ip3=`/bin/echo $ip2 | sed 's?\.[0-9]*$??'`
    ip4=${ip#${ip1}.}

    for i in $ip $ip1 $ip2 $ip3
    do
	if [ -a db.$i ] 
	then
	    rnlfile=db.$i
	    return 0
	fi
    done
    return 1
}

#-------------------------------------------------------------------------------
#
#
# Start of adding /etc/hosts section
#
#
#-------------------------------------------------------------------------------

################################################################################
# generate the hosts entry
# $1 is ip
# $2 is name w/o domain
# $3 is domain
################################################################################
function ha {
    $NLECHO "protoMess  ha $1 $2 $3"
    cat << SEOF > /tmp/awkha.$$
    BEGIN { printed = 0 
	    done = 0
	    split("$1", ipg, ".")
	  }
    {
      if (!printed) {
        digit=substr(\$0,1,1)
        if ( digit != "#" ) {
          n = split(\$1, ip, ".")
	  if (n == 4) {
            for (i=1; i<5 && !done && !printed; i++) {
	      if (ipg[i] > ip[i]) {
	        done = 1
	      } else if (ipg[i] < ip[i]) {
	        printf "%s\\t%s\\t%s.%s\\t# %s\n", "$1", "$2", "$2",
	  				    "$3", "$product"
	        printed = 1
	      }
            }
	  }
        } 
        done = 0
      }
      print \$0
    }
    END { if (!printed) {
	  printf "%s\\t%s\\t%s.%s\\t# %s\n", "$1", "$2", "$2",
					    "$3", "$product"
      }
    }
SEOF
awk -f /tmp/awkha.$$ $hostsfile > $hostsfile.$$
if [ $? -eq 0 ]
then
    mv $hostsfile.$$ $hostsfile
    chmod 644 $hostsfile
fi
rm -f /tmp/awkha.$$
}

################################################################################
#
# if its there, no action
# if its there with a different ip, remove that, insert new
# if its there with a different name, error
# $1 is ip
# $2 is name
################################################################################
function etchostsAdd {
# echo the line of
# ip	name to /etc/hosts
$NLECHO "protoMess  egrep -q "^$1" $hostsfile"
egrep -q "^$1" $hostsfile 
if [ $? -ne 0 ]
then
    $NLECHO "protoMess  This ip is not there."
    egrep -q "$terminal[^a-zA-Z0-9]" $hostsfile
    if [ $? -ne 0 ]
    then
	$NLECHO "protoMess  This name is not there."
	ha $1 $terminal $domain
	return 0
    else
	$NLECHO "protoMess  This name is there, different ip."
	egrep -v "$terminal[^a-zA-Z0-9]" $hostsfile > $hostsfile.$$
	mv $hostsfile.$$ $hostsfile
	chmod 644 $hostsfile
	ha $1 $terminal $domain
	return 0
    fi
else
    $NLECHO "protoMess  This ip is there"
    egrep "^$1" $hostsfile | egrep -q "$terminal[^a-zA-Z0-9]" 
    if [ $? -ne 0 ]
    then
	$NLECHO "protoMess  Different name assigned this ip "
	return 5
    else
	$NLECHO "protoMess  No action necessary"
	return 1
    fi
fi
}


#-------------------------------------------------------------------------------
#
#
# Start of removing /etc/hosts section
#
#
#-------------------------------------------------------------------------------


################################################################################
#
# if its there, no action
# if its there with a different ip, remove that, insert new
# if its there with a different name, error
# $1 is ip
# $2 is name
################################################################################
function etchostsSub {
$NLECHO "protoMess  etchostsSub invoked as $1 $2"
cat << SEOF > /tmp/awkehs.$$
{
    if ( ! ( \$1 == "$1" || \$2 == "$2" || \$3 == "$2" ) )
	print \$0
}
SEOF

awk -f /tmp/awkehs.$$ $hostsfile > $hostsfile.$$
if [ $? -eq 0 ]
then
    mv $hostsfile.$$ $hostsfile
    chmod 644 $hostsfile
fi
rm -f /tmp/awkehs.$$

$NLECHO "protoMess  Done etchostsSub"
}

#-------------------------------------------------------------------------------
#
#
# Start of adding NIS section
#
#
#-------------------------------------------------------------------------------

################################################################################
# 
# This function adds a terminal to NIS: it adds it to /etc/hosts, and then
# runs make from /usr/etc/yp
#
# $1 is ip
# $2 is name
################################################################################
function nisAdd {
etchostsAdd $1 $2
if [ $? -eq 0 ]
then
    cd $usretcypdir
    make 1>/dev/null 2>/dev/null
fi
}

#-------------------------------------------------------------------------------
#
#
# Start of removing NIS section
#
#
#-------------------------------------------------------------------------------

################################################################################
# 
# This function removes a terminal from NIS: it removes from /etc/hosts,
# and then runs make from /usr/etc/yp
#
# $1 is ip
# $2 is name
################################################################################
function nisSub {
etchostsSub $1 $2
if [ $? -eq 0 ]
then
    cd $usretcypdir
    make 1>/dev/null 2>/dev/null
fi
}



#-------------------------------------------------------------------------------
#
#
# Start of adding DNS / BIND section
#
#
#-------------------------------------------------------------------------------

################################################################################
# $1 name of db file
# $2 ip
# $3 name
################################################################################
function AddReverseLookup {
if [ -w $1 ]
then
    cat << SEOF > /tmp/awkarl.$$
    BEGIN { 
	   printed = 0
	   numdots = split("$1", names, ".")
	   split("$2", digits, ".");
	   if (numdots == 4) {
	    ip = sprintf ( "%d", digits[4])
	   } else if (numdots == 3) {
	    ip = sprintf ( "%d.%d", digits[4],digits[3])
	   } else if (numdots == 2) {
	    ip = sprintf ( "%d.%d.%d", digits[4],digits[3],digits[2])
	   }
	  }
    {
       if ( !printed && \$3 == "PTR" && \$1 >= ip) {
	printf "%s\\tIN\\tPTR\\t%s. ;$product\n",ip,"$3"
	printed = 1
       }
       print \$0
    }
    END {  if ( !printed ) {
	 printf "%s\\tIN\\tPTR\\t%s. ;$product\n",ip,"$3"
       }
    }
SEOF
    awk -f /tmp/awkarl.$$ $1 > $1.$$
    if [ $? -eq 0 ]
    then
	mv $1.$$ $1
	chmod 644 $1
	return 0
    else
	rm -f /tmp/awkarl.$$
	return 1
    fi
return 1
fi
}


################################################################################
# $1 name of db file
# $2 name
################################################################################
function DelReverseLookup {
$NLECHO "protoMess  DelReverseLookup $1 $2"
if [ -w $1 ]
then
cat << SEOF > /tmp/awkdrl.$$
BEGIN {  }
    {
       if ( ! index(\$4,"$2" ) ) {
	 print \$0
       } 
    }
END { }
SEOF
    awk -f /tmp/awkdrl.$$ $1 > $1.$$
    if [ $? -eq 0 ]
    then
	mv $1.$$ $1
	chmod 644 $1
	return 0
    else
	rm -f /tmp/awkdrl.$$
	return 1
    fi
else
    return 1
fi
}

################################################################################
# $1 name of db file
# $2 ip address
# $3 name (w/o domain)
################################################################################
function AddDomainInfo {
if [ -w $1 ]
then
cat << SEOF > /tmp/awkadi.$$
BEGIN { printed = 0; done = 1 }
    {
      if ( !printed && \$3 == "A" && \$4 != "127.0.0.1" ) {
	# must do ip address comparison now
	ip="$2"
	ip1=\$4
	split(ip, given, ".")
	split(ip1, file, ".")
	for ( i=1 ; !done && !printed && i<5 ; i++ ) {
	      if ( given[i] > file[i] ) {
		done = 1
	      } else if ( given[i] < file[i] ) {
	        printf "%s", "$3"
		for (i=length("$3");i<16;i++)
		    printf " "
		printf "IN\\tA\\t%s ;$product\n","$2"
                printed = 1
	      } 
	    }
	  } 
	  done = 0
	  print \$0
	}
    END { if ( !printed ) {
		printf "%s\\tIN\\tA\\t%s ;$product\n","$3","$2"
	  }
	}
SEOF
    awk -f /tmp/awkadi.$$ < $1 > $1.$$
if [ $? -eq 0 ]
then
    mv $1.$$ $1
    chmod 644 $1
    return 0
else
    return 1
fi
else
    return 1
fi
}


################################################################################
#
# remove from the db.$domain file the entries, include MX
# $1 name of db file
# $2 name (w/o domain)
################################################################################
function DelDomainInfo {
$NLECHO "protoMess  DelDomainInfo $1 $2"
if [ -w $1 ]
then
    cat << SEOF > /tmp/awkddi.$$
    BEGIN { deleting=0 }
	{
	    if ( \$3 != "MX" && !deleting ) {
		if ( \$1 != "$2" ) {
		  print \$0
		}
	    } else {
		if ( \$1 == "$2" ) {
		    deleting = 1
		} else if ( \$2 != "MX" ) {
		    deleting = 0
		}
		if (!deleting) {
		    print \$0
		}
	    }
	}
    END { }
SEOF
    awk -f /tmp/awkddi.$$ < $1 > $1.$$
if [ $? -eq 0 ]
then
    mv $1.$$ $1
    chmod 644 $1
    return 0
else
    rm -f /tmp/awkddi.$$
    return 1
fi
else
    return 1
fi
}


################################################################################
# $1 --> name of db file
# returns 0 on success
# 1 on failure
################################################################################
function UpdateSerialNumber {
if [ -w $1 ]
then
$NLECHO "protoMess  usn for $1"
    cat << SEOF > /tmp/awksusn.$$
    BEGIN 	  { state=0 }
	{
	    if (state == 1) {
		#
		# This covers the second line serial number
		#
		sn=\$1
		snn=sn + 1
		sub(sn, snn )
		print \$0
		state=2
	    } else if (state == 2) {
		#
		# This covers the rest
		#
		print \$0
	    }
	}

	#
	# Find the SOA record. Is it one line or split?
	#
	/SOA/ { if (\$NF == "(") {
		    print \$0
		    state=1
		} else {
		    sn=\$6
		    snn=sn + 1
		    sub(sn, snn )
		    print \$0
		    state=2
		}
	      }

    END       { }
SEOF

    awk -f /tmp/awksusn.$$ $1 > $1.$$ 
    if [ $? -eq 0 ]
    then
	mv $1.$$ $1 
	chmod 644 $1
	rm -f /tmp/awksusn.$$ 
	return 0
    else
	return 1
    fi
else
    return 1
fi
}

################################################################################
#
# add to /etc/hosts
# find the dir for this database.
# add to appropriate db.* file.
# send SIGHUP to named
#
# $1 is ip
# $2 is name
#
################################################################################
function dnsAdd {
    directory=`grep ^directory $namedboot | awk '{ print $2 }'`
    $NLECHO "protoMess  dir = $directory"
    $NLECHO "protoMess  domain == $domain namedboot == $namedboot"
    cat << SEOF > /tmp/awkdbd.$$
    {
	if (\$1 == "primary" && \$2 == "$domain")
	    print \$3
    }
SEOF
    dbd=`awk < $namedboot -f /tmp/awkdbd.$$`
    rm -f /tmp/awkdbd.$$

    # put it in hosts in case user does a host_to_named 
    etchostsAdd $1 $2

    # get the reverse name lookup files
    #
    for dir in $directory
    do
	$NLECHO "protoMess  cd\'ing to $dir"
	cd $dir
	CheckForDBFile $1
	if [ $? -eq 0 ]
	then
	    $NLECHO "protoMess  Adding to $rnlfile"
	    if egrep -q $2 $rnlfile
	    then
		$NLECHO "protoMess  $2 already in $rnlfile"
		return 5
	    else
		# check for this ip in there already.
		if egrep -q "$ip4[ \\t]" $rnlfile
		then
		    $NLECHO "protoMess  $1 already in $rnlfile "
		    return 5
		else
		    $NLECHO "protoMess  updating serial number in $dir/$rnlfile"
		    UpdateSerialNumber $rnlfile
		    $NLECHO "protoMess  adding $ip4 $2 to $dir/$rnlfile"
		    AddReverseLookup $rnlfile $1 $2
		fi
	    fi
	fi
    done


    # get the authoritative for domain file
    #
    $NLECHO "protoMess  $dbd"
    for dir in $directory
    do
	$NLECHO "protoMess  cd\'ing to $dir"
	cd $dir
	$NLECHO "protoMess  the file is $dbd"
	# if $dbd is here, use it
	$NLECHO "protoMess  Updating serial number in $dir/$dbd"
	UpdateSerialNumber $dbd
	$NLECHO "protoMess  Adding $1 $terminal to $dir/$dbd"
	AddDomainInfo $dbd $1 $terminal
    done

    sig_named restart 1>/dev/null
    return 0
}

#-------------------------------------------------------------------------------
#
#
# Subtracting DNS section
#
#
#-------------------------------------------------------------------------------

################################################################################
#
# Take ip name and sub from dns
# $1 is ip
# $2 is name
#
################################################################################
function dnsSub {

    directory=`grep ^directory $namedboot | awk '{ print $2 }'`
    $NLECHO "protoMess  dir = $directory"

    etchostsSub $1 $2

    # get the reverse name lookup files
    #
    for dir in $directory
    do
	$NLECHO "protoMess  cd\'ing to $dir"
	cd $dir
	CheckForDBFile $1
	if [ $? -eq 0 ]
	then
	    $NLECHO "protoMess  Removing from $rnlfile"
	    DelReverseLookup $rnlfile $2
	    UpdateSerialNumber $rnlfile
	fi
    done

    $NLECHO "protoMess  domain == $domain namedboot == $namedboot"
    cat << SEOF > /tmp/awkdbd.$$
    {
	if (\$1 == "primary" && \$2 == "$domain")
	    print \$3
    }
SEOF
    dbd=`awk < $namedboot -f /tmp/awkdbd.$$`
    rm -f /tmp/awkdbd.$$
    $NLECHO "protoMess  sub:domain file is $dbd"
    # get the authoritative for domain file
    #
    for dir in $directory
    do
	$NLECHO "protoMess  the file is $dbd"
	$NLECHO "protoMess  cd\'ing to $dir"
	cd $dir
	# if $dbd is here, use it
	$NLECHO "protoMess  Updating serial number in $dir/$dbd"
	UpdateSerialNumber $dbd
	$NLECHO "protoMess  Deleting $1 $terminal from $dir/$dbd"
	DelDomainInfo $dbd $terminal
    done

    sig_named restart 1>/dev/null
    return 0
}

#-------------------------------------------------------------------------------
#
#
# Adding logic controller
#
#
#-------------------------------------------------------------------------------

################################################################################
#
# Take ip name and add to the previously determined method
# $1 is ip
# $2 is name
#
################################################################################
function DoAdd {
    if [ "$nis" = "1" ]
    then
	$NLECHO "protoMess  doing nis add"
	nisAdd $1 $2
    fi

    if [ "$dns" = "1" ]
    then
	$NLECHO "protoMess  doing dns add"
	dnsAdd $1 $2
    fi

    if [ "$hosts" = "1" ]
    then
	$NLECHO "protoMess  doing hosts add"
	etchostsAdd $1 $2
    fi
}

#-------------------------------------------------------------------------------
#
#
# Subtracting logic controller
#
#
#-------------------------------------------------------------------------------

################################################################################
#
# Take ip name and remove from the previously determined method
# $1 is ip
# $2 is name
#
################################################################################
function DoSub {
    if [ "$nis" = "1" ]
    then
	$NLECHO "protoMess  doing nis sub"
	nisSub $1 $2
    fi

    if [ "$dns" = "1" ]
    then
	$NLECHO "protoMess  doing dns sub"
	dnsSub $1 $2
    fi

    if [ "$hosts" = "1" ]
    then
	$NLECHO "protoMess  doing hosts sub"
	etchostsSub $1 $2
    fi
}

#-------------------------------------------------------------------------------
#
#
# Setup and run part.
#
#
#-------------------------------------------------------------------------------

################################################################################
#
# main part of script
#
################################################################################

hostname=`uname -n`
# domain is the domain of the terminal to add
domain=`/bin/echo $1 | sed -e 's?[^.]*.??'`
if [ "$domain" = "" ]
then
    # default to host's domain
    domain=`nslookup $hostname | grep "Name:" | sed -e 's?[^.]*??' -e 's?\.??'`
fi
/bin/echo "Domain: $domain"
terminal=`/bin/echo $1 | sed -e 's?\([^.]*\).*?\1?'`
/bin/echo "Terminal: $terminal"
soa=0
dns=0
nis=0
hosts=0
nohosts=0
hostsfile=/etc/hosts
usretcypdir=/usr/etc/yp
namedboot=/etc/named.boot
rnlfile=
product="ENWARE X Terminal Manager"

LOG=/tmp/agentlog
rm -f $LOG

if [ $# -ne 3 ]
then
    $NLECHO "addHostsUsage $0"
    exit 1
fi

if [ "$3" = "DELETE" ]
then
    Adding=0
elif [ "$3" = "ADD" ]
then
    Adding=1
else
    $NLECHO "addHostsUsage $0"
	# Debug "Usage: $0 ip name ADD | DELETE"
    exit 1
fi

CheckSOA 
if [ $? -ne 1 ]
then
    $NLECHO "notAuthoritative $1 $hostname"
    exit 3
fi

CheckMethod
if [ "$Adding" != 0 ]
then
    DoSub $2 $1 
    DoAdd $2 $1
else
    DoSub $2 $1
fi

exitStat=$?

exit $exitStat








