filesystem: "root"
mode: 0755
path: "/etc/NetworkManager/dispatcher.d/30-resolv-prepender"
contents:
  inline: |
    #!/bin/bash
    set -eo pipefail
    IFACE=$1
    STATUS=$2

    {{if .Proxy -}}
    {{if .Proxy.HTTPProxy -}}
    HTTP_PROXY={{.Proxy.HTTPProxy}}
    {{end -}}
    {{if .Proxy.HTTPSProxy -}}
    HTTPS_PROXY={{.Proxy.HTTPSProxy}}
    {{end -}}
    {{if .Proxy.NoProxy -}}
    NO_PROXY={{.Proxy.NoProxy}}
    {{end -}}
    {{end -}}

    # If $DHCP6_FQDN_FQDN is not empty and is not localhost.localdomain
    [[ -n "$DHCP6_FQDN_FQDN" && "$DHCP6_FQDN_FQDN" != "localhost.localdomain" && "$DHCP6_FQDN_FQDN" =~ "." ]] && hostnamectl set-hostname --static --transient $DHCP6_FQDN_FQDN
    case "$STATUS" in
        up|down|dhcp4-change|dhcp6-change)
        logger -s "NM resolv-prepender triggered by ${1} ${2}."

        # Ensure resolv.conf exists before we try to run podman
        cp /var/run/NetworkManager/resolv.conf /etc/resolv.conf

        NAMESERVER_IP=$(/usr/bin/podman run --rm \
            --authfile /var/lib/kubelet/config.json \
            --net=host \
            {{ .Images.baremetalRuntimeCfgImage }} \
            node-ip \
            show \
            "{{.Infra.Status.PlatformStatus.BareMetal.APIServerInternalIP}}" \
            "{{.Infra.Status.PlatformStatus.BareMetal.IngressIP}}")
        DOMAIN="{{.EtcdDiscoveryDomain}}"
        if [[ -n "$NAMESERVER_IP" ]]; then
            logger -s "NM resolv-prepender: Prepending 'nameserver $NAMESERVER_IP' to /etc/resolv.conf (other nameservers from /var/run/NetworkManager/resolv.conf)"
            sed -e "/^search/d" \
                -e "/Generated by/c# Generated by KNI resolv prepender NM dispatcher script\nsearch $DOMAIN\nnameserver $NAMESERVER_IP" \
                /var/run/NetworkManager/resolv.conf > /etc/resolv.tmp
        fi
        # Only leave the first 3 nameservers in /etc/resolv.conf
        sed -i ':a $!{N; ba}; s/\(^\|\n\)nameserver/\n# nameserver/4g' /etc/resolv.tmp
        mv -f /etc/resolv.tmp /etc/resolv.conf
        ;;
        *)
        ;;
    esac
