#!/bin/bash

IB_STDIN=""
read -t 0 -N 0 && IB_STDIN=$(cat)

ts_now=$(date +%s)

EXPIRATION=86400
STOREFILE=/var/lib/check_mk_agent/ipoib.nodes
OUTPUTFILE=/tmp/ipoib.output
PIDFILE=/tmp/ipoib.pid

stored="$(cat $STOREFILE 2>/dev/null)"

type ibhosts &>/dev/null
if [[ $? == 0 ]] ; then

   still_running="no"
   pid_ipoib=$(cat $PIDFILE 2>/dev/null)
   if [ ${#pid_ipoib} -gt 0 ] ; then
       ps ax | awk -v PID=$pid_ipoib '{if($1==PID && $5=="/bin/bash")exit 1}' > /dev/null 2> /dev/null
       if [ $? -eq 1 ] ; then
          still_running="$pid_ipoib"
       fi
   fi
   
   echo '<<<ipoib>>>'
   
   echo "[[local]]"
   ifconfig 2>/dev/null | awk -v host=$(hostname -f) -F ':|[[:space:]]*' 'BEGIN {dev="" } {if ($0 ~ /^\S+/) dev=""; if ($0 ~ /^ib[0-9]+/) dev=$1; if (dev != "" && $0 ~ /.*inet\s+add{0,1}r/ ) print host " " dev " " $4}'

   echo "[[ping]]"
   
   cat $OUTPUTFILE 2>/dev/null

   if [ "$still_running" != "no" ]; then
       echo "MESSAGE: pid ${still_running} still exists"
       exit 0
   fi

   # projdu ulozene hosty a ten ktery je stary, zapomenu
  if [ "$still_running" == "no" ]; then
   nodes=""   
   for i in $stored ; do
       host=$(echo "$i" | cut -f1 -d'|')
       ip=$(echo "$i" | cut -f2 -d'|')
       ts=$(echo "$i" | cut -f3 -d'|')

       # pokud je i v prave prichozich date, aktualizuju ip a ts
       for new in $IB_STDIN ; do
           new_host=$(echo "$new" | cut -f1 -d'|')
           new_ip=$(echo "$new" | cut -f2 -d'|')
           if [[ $host == $new_host ]] ; then
               ip=$new_ip
               ts=$ts_now
           fi
       done

       if [ $((ts+EXPIRATION)) -gt $ts_now ] ; then
           nodes="$nodes $host|$ip|$ts"
       fi

   done

   # pridam nove uzly z prave prichozich dat
   for new in $IB_STDIN ; do
       new_host=$(echo "$new" | cut -f1 -d'|')
       new_ip=$(echo "$new" | cut -f2 -d'|')

       found=0
       for i in $nodes ; do
           host=$(echo "$i" | cut -f1 -d'|')
           if [[ $host == $new_host ]] ; then
               found=1
           fi
       done

       if [ $found == 0 ] ; then
           nodes="$nodes $new_host|$new_ip|$ts_now"
       fi
   done

   rm $OUTPUTFILE 2>/dev/null
   # platne uzly otestuju na ping
   for i in $nodes ; do
       host=$(echo "$i" | cut -f1 -d'|')
       ip=$(echo "$i" | cut -f2 -d'|')
       ts=$(echo "$i" | cut -f3 -d'|')

       ping ${ip} -c 1 -w 10 &>/dev/null
       if [[ $? == 0 ]] ; then
           echo "$host OK" >> $OUTPUTFILE
       else
           echo "$host --" >> $OUTPUTFILE
       fi
   done 

   # platne uzly ulozim
   echo $nodes > $STOREFILE 
  fi &>/dev/null & disown 2>/dev/null
  echo "$!" > $PIDFILE
  
fi
