#!/bin/bash

# What: The Xymon ghost report is a list of systems that delivered reports
#       without being configured in the hosts.cfg file.  This script reads
#       the ghost list and generates a hosts.cfg file to contain them, so
#       that the various reports are readable/actionable almost immediately.
#       Email is also sent to the Xymon admin so that the ghost list may
#       be dispersed among the other hosts.cfg files as appropriate.
#
# When: 2011-11-03
#
# Blame: Ralph Mitchell

# who do we call?
GHOSTBUSTERS="user-f2fbf7759e95@xymon.invalid"

# Somewhere to stash the list.
# This file needs to be included by /home/xymon/server/etc/hosts.cfg
GHOSTCFG=/home/xymon/server/etc/hosts.d/ghosts

# set up initial page content
if [ ! -f $GHOSTCFG ]; then 
  echo "# hosts that just showed up one day"  > $GHOSTCFG
  echo "#"                                   >> $GHOSTCFG
  echo "page ghosts Unconfigured Clients"    >> $GHOSTCFG
  echo "group-compress Ghost List"           >> $GHOSTCFG 
fi

# count the current ghost list
ZOMBIES=`grep -c noconn $GHOSTCFG`

# anything in the ghost list?
GHOSTLIST=`/home/xymon/server/bin/xymon localhost ghostlist`
if [ -n "$GHOSTLIST" ]; then 
  # got something, make up a header for the new entries
  HEADER="# added: `date --rfc-3339=seconds`" 

  # process the ghostlist
  echo "$GHOSTLIST" | while read LINE
  do 
    # extract host name
    HOST=`echo $LINE | cut -f1 -d'|'` 

    # skip "linux.nexnet.navy.mil" - I think this comes from register imaging
    if [ "$HOST" = "linux.nexnet.navy.mil" ]; then 
      continue
    fi 

    # is this host already in the ghost list?
    if [ `grep -c "$HOST" $GHOSTCFG` -eq 0 ]; then 
      # not found, add it
      if [ -n "$HEADER" ]; then 
        # for first new host in this run, add the header
        echo "$HEADER" >> $GHOSTCFG
        # only want the header once per block
        HEADER="" 
      fi

      # if it's in the DNS, we might as well use its proper IP
      DNS=`nslookup $HOST | grep -A 1 'Name:'`
      if [ $? -eq 0 ]; then 
        # found it, get the IP
        HOSTIP=`echo $DNS | cut -f4 -d' '` 
      else
        # not in the DNS
        HOSTIP="0.0.0.0" 
      fi
    
      # the "noconn" option stops xymon from trying to ping the host
      echo "$HOSTIP        $HOST                # noconn" >> $GHOSTCFG 
    fi
  done 

  # did we add anything to the ghost file?
  COUNT=`grep -c noconn $GHOSTCFG`
  COUNT=`expr $COUNT - $ZOMBIES`
  if [ $COUNT -gt 0 ]; then 
    # let someone know we need to re-process the ghost file
    grep noconn $GHOSTCFG | \ 
    mailx -s "Xymon Ghost list: $COUNT new members" $GHOSTBUSTERS
  fi 
fi

exit 0 
