#!/bin/bash

which crictl >/dev/null 2>&1
if [ "$?" != "0" ] ; then
  sleep 120
  systemctl restart machine-config-daemon-pull.service
  systemctl restart machine-config-daemon-host.service
  exit 0
fi

if [ "$2" = "dhcp4-change" ] || [ "$2" = "dhcp6-change" ] || [ "$2" = "up" ] || [ "$2" = "connectivity-change" ]; then
  sleep 2
  IP=$(/bin/hostname -I | awk '{print $1}')
  if [ "$IP" != "" ] ; then
    grep -q $IP /etc/resolv.conf
    if [ "$?" != "0" ] ; then
      sed -i 's/{{ cluster }}.{{ domain }}//' /etc/resolv.conf
      sed -i 's/search /search {{ cluster }}.{{ domain }} /' /etc/resolv.conf
      sed -i "/nameserver.* # coredns/d" /etc/resolv.conf
      sed -i "0,/nameserver/s/nameserver/nameserver $IP #coredns\n&/" /etc/resolv.conf
      {%- if ipv6 %}
      GATEWAY=$( tail -1 /etc/resolv.conf  | cut -f2 -d" ")
      ip -6 r | grep -q default || ip -6 r add default via $GATEWAY
      {%- endif %}
    fi
  fi
fi
