#!/bin/bash

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

if [ $(ymc_is_chroot) -ne 0 ]; then
  echo "WARNING: $0 can not be run inside a chroot..." 1>&2
  exit 0
fi

if [ "$1" == '--deconfigure' ]; then
  echo "### Deconfigured resolv.conf(5) - feel free to adapt it to fit with your needs!" > /etc/resolv.conf
  echo "nameserver 8.8.8.8" >> /etc/resolv.conf
  echo "nameserver 8.8.4.4" >> /etc/resolv.conf
else
  do_dns_rotate=1
  dns_ips=""

  echo -n "INFO: Initially searching for internal nameservers in network 'lan'..." 1>&2
  possible_nameservers=$(hostname -s | socat -T 10 -t 3 STDIO UDP4-DATAGRAM:224.0.0.153:5533,ip-add-membership=224.0.0.153:lan,ip-multicast-if=$(ymc_get_primary_ip_for_network lan) 2>/dev/null)
  if [ $? -ne 0 ] || \
     [ -z "$possible_nameservers" ]; then
    echo "DONE [none found]" 1>&2
    ### YCLEGACY-SUPPORT //start
    # NOTE: We should stop here in future with an error - for now we support YCLEGACY
    echo "WARNING: No internal nameservers in network 'lan' found - falling back to legacy detection mode..." 1>&2

    ### Try to figure out the cluster-id
    cluster_id=$(ymc_caluclated_cluster_id)
    if [ $? -ne 0 ] || \
       [ -z "$cluster_id" ]; then
      echo "ERROR: Can not get the cluster-id..." 1>&2
    fi


    dns_infos_yclegacy=$(dig @224.0.0.251 -b $(ymc_get_primary_ip_for_network lan) -p 5353 _ymcClusterDNS._udp.local ptr +noall +answer +nocl +nottlid +time=2 | sed -r 's/[[:space:]]+/|/g' | grep -E -e "^dns-internal[^.]*\.$cluster_id\.local\.|A|10\.$cluster_id" | LC_ALL=C sort -g -r | uniq)
    for dns_info in $dns_infos_yclegacy
    do
      dns_numbered_service=$(echo $dns_info | cut -d '|' -f 1 --only-delimited)
      dns_ip=$(echo $dns_info | cut -d '|' -f 3 --only-delimited | sed -r 's/[^0-9.]//g')
      if [ $(echo $dns_numbered_service | grep -c -E -e '-[0-9]+') -le 0 ]; then
        dns_ips="$dns_ip $dns_ips"
        do_dns_rotate=0
      else
        dns_ips="$dns_ips $dns_ip"
      fi
    done
    dns_infos_yclegacy=""
    ### YCLEGACY-SUPPORT //end
  else
    echo "DONE [found at least $(echo $possible_nameservers | wc -w) internal nameserver(s)]" 1>&2

    for possible_nameserver in $possible_nameservers
    do
      echo -n "INFO: Asking '$possible_nameserver' for a ha-nameserver 'dns-internal.cluster'..." 1>&2
      ha_nameserver_ip=$(dig @$possible_nameserver dns-internal.cluster A +short +time=2 2>/dev/null)
      if [ $? -eq 0 ] && \
         [ "$ha_nameserver_ip" != "" ]; then
        do_dns_rotate=0
        dns_ips="$dns_ips $ha_nameserver_ip"
        echo "DONE [found: $ha_nameserver_ip]" 1>&2
      else
        echo "DONE [none found]" 1>&2
      fi

      echo -n "INFO: Asking '$possible_nameserver' for further dns-servers for service 'dns-internal'..." 1>&2
      unordered_dns_ips=""
      for further_nameserver in $(dig @$possible_nameserver dns-internal.services txt +short +time=2 2>/dev/null | sed -r 's/"//g')
      do
        further_nameserver_ip=$(dig @$possible_nameserver $further_nameserver.cluster A +short +time=2 2>/dev/null)
        if [ $? -eq 0 ] && \
           [ "$further_nameserver_ip" != "" ]; then
          unordered_dns_ips="$unordered_dns_ips $further_nameserver_ip"
        fi
      done
      echo "DONE [found $(echo $unordered_dns_ips | wc -w) further nameserver(s)]" 1>&2

      if [ -n "$dns_ips" ] || \
         [ -n "$unordered_dns_ips" ]; then
        break
      fi
    done

    echo -n "INFO: Ordering found further nameservers by network latency..." 1>&2
    ordered_dns_ips=$(for unordered_dns_ip in $unordered_dns_ips
                      do
                        echo "$(LC_ALL=C ping -w 10 -q -n -c 10 -i 0.2 $unordered_dns_ip 2>/dev/null \
                                | grep -F 'rtt min/avg/max/mdev = ' \
                                | cut -d '=' -f 2 \
                                | cut -d '/' -f 2) \
                              99999 - $unordered_dns_ip"
                      done \
                      | sed -r 's/^ +//' \
                      | grep -v -E -e  '^-' \
                      | sort -n \
                      | sed -r 's/^[^-]* - //')
    dns_ips="$dns_ips $ordered_dns_ips"
    echo "DONE" 1>&2
  fi

  if [ $(echo -n $dns_ips | wc -c) -eq 0 ]; then
    echo "ERROR: No valid nameservers found - not updating '/etc/resolv.conf'" 1>&2
    exit 1
  fi

  ### Generate a proper /etc/resolv.conf
  echo "# Dynamic resolv.conf(5) file generated by $(basename $0)" > /etc/resolv.conf
  echo "#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN" >> /etc/resolv.conf
  for dns_ip in $dns_ips
  do
    echo "INFO: Using nameserver $dns_ip" 1>&2
    echo "nameserver $dns_ip" >> /etc/resolv.conf
  done
  echo "domain cluster" >> /etc/resolv.conf
  if [ $do_dns_rotate -eq 1 ]; then
    echo "options rotate timeout:1 attempts:2" >> /etc/resolv.conf
  else
    echo "options timeout:1 attempts:2" >> /etc/resolv.conf
  fi
fi
