#!/bin/bash -xe

if [ -z "$PROVISIONING_IP" ]; then
    echo "ERROR: PROVISIONING_IP environment variable unset."
    exit 1
fi

if [ -z "$PROVISIONING_INTERFACE" ]; then
  # If no provisioning interface is specified, then we're probably in
  # the mode where the provisioning network is optional, so to avoid a
  # hard dependency of forcing users to specify the interface, we detect
  # which network interface has the IP's from the machine network.
  IP_ONLY=$(echo "$PROVISIONING_IP" | cut -d/ -f1)

  # See if we already have the IP on an interface
  PROVISIONING_INTERFACE=$(ip -j addr | jq -r -c ".[].addr_info[] | select(.local == \"$IP_ONLY\") | .label")

  # If not, let's figure out what interface it should go on
  if [ -z "$PROVISIONING_INTERFACE" ]; then
    PROVISIONING_INTERFACE=$(ip -j route get "$IP_ONLY" | jq -r '.[] | select(.dev != "lo") | .dev')
  fi
else
  # Get rid of any DHCP addresses only if we have a dedicated
  # provisioning interface
  /usr/sbin/ip address flush dev "$PROVISIONING_INTERFACE"
fi

if [ -z "$PROVISIONING_INTERFACE" ]; then
  ip addr show
  echo "ERROR: Could not find suitable interface for \"$PROVISIONING_IP\""
  exit 1
fi

# In case the IP has lapsed since we set it in the init container.
/usr/sbin/ip addr add "$PROVISIONING_IP" dev "$PROVISIONING_INTERFACE" valid_lft 10 preferred_lft 10 || true

while true; do
    # https://bugzilla.redhat.com/show_bug.cgi?id=1908302
    # Toggling addr_gen_mode prompts the link local address to be reapplied in cases
    # where it is lost.
    ip -o addr show dev "$PROVISIONING_INTERFACE" scope link | grep -q " fe80::" || \
    ( echo 1 > "/proc/sys/net/ipv6/conf/$PROVISIONING_INTERFACE/addr_gen_mode" ; echo 0 > "/proc/sys/net/ipv6/conf/$PROVISIONING_INTERFACE/addr_gen_mode" )
    /usr/sbin/ip addr change "$PROVISIONING_IP" dev "$PROVISIONING_INTERFACE" valid_lft 10 preferred_lft 10
    sleep 5
done

