#!/bin/bash

### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash

conf_dir="/etc/fliwi/services/dns-internal/ha_mgmdns"
dnsmasq_dir="/etc/dnsmasq-fliwi_mgmdns_hosts"

if [ ! -d "$dnsmasq_dir" ]; then
  echo "Directory $dnsmasq_dir is missing!" 1>&2
  exit 1
fi

lockFile="/tmp/fliwi_ha_mgm_dns.lock"

### Do not run if an other one is running
if [ -e $lockFile ]; then
  echo "There seems to be an other instance running, since '$lockFile' exists!" 1>&2
  exit 1
fi

### generate look
/bin/date +%s > $lockFile


for conf_file in $(ls $conf_dir)
do
  service_name=$(echo $conf_file | sed -r 's/\.conf$//')
  if [ -f "$dnsmasq_dir/$service_name" ]; then
    rm -f $dnsmasq_dir/$service_name
  fi

  ### Source the config it provides:
  ###  string  protocol
  ###  integer port
  ###  array   ip_targets
  . $conf_dir/$conf_file

  for ip_target in "${ip_targets[@]}"
  do
    echo "INFO: Checking IP $ip_target..."
    if [ $(ymc_is_host_alive $ip_target) -ne 1 ]; then
      echo "WARNING: IP $ip_target is offline !" 1>&2
    else
      healthcheck_status=0

      if [ "$port" == "3306" ] && \
         [ "$protocol" != 'udp' ]; then
        ### We deal with mysql...
        /usr/bin/fliwi-mysql-ping $ip_target 2>/dev/null 1>/dev/null
        healthcheck_status=$?
      else
        protocol_switch=''
        if [ "$protocol" == 'udp' ]; then
          protocol_switch='-u'
        fi
        ### Run netcat to check the ip using protocol and port
        nc -w 2 -z $protocol_switch $ip_target $port 2>/dev/null 1>/dev/null
        healthcheck_status=$?
      fi


      if [ $healthcheck_status -eq 0 ]; then
        service_num=$(echo $ip_target |cut -d '.' -f 4)
        echo "INFO: Service on IP $ip_target using port $port and protocol $protocol is online..."
        echo -e "$ip_target\t$service_name-$service_num\t$service_name\n" >> $dnsmasq_dir/$service_name
      else
        echo "WARNING: Service on IP $ip_target using port $port and protocol $protocol is offline !" 1>&2
      fi
    fi
  done

  ### Unset at least the ip_targets array
  unset ip_targets
done


# Send a SIGHUP [1] to dnsmasq to advice a reload
if [ -f "/var/run/dnsmasq/dnsmasq.pid" ]; then
  dnsmasq_pid=$(cat /var/run/dnsmasq/dnsmasq.pid)
  if [ "$dnsmasq_pid" != '' ] && [ $(pidof dnsmasq) -eq $dnsmasq_pid ]; then
    kill -1 $dnsmasq_pid
  else
    echo "Could not reload DNSMASQ, advising restart!" 1>&2
    /etc/init.d/dnsmasq restart
  fi
else
  echo "Not reloading DNSMASQ, as it is not running..." 1>&2
fi


### unlook
/bin/rm -f $lockFile

exit 0

