#!/bin/bash -xe

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

if [ -z "$PROVISIONING_INTERFACE" ]; then
  if [ -n "${PROVISIONING_MACS}" ]; then
    for mac in ${PROVISIONING_MACS//,/ } ; do
      if ip -br link show up | grep -q "$mac"; then
        PROVISIONING_INTERFACE=$(ip -br link show up | grep "$mac" | cut -f 1 -d ' ')
        break
      fi
    done
  fi
fi

if [ -n "$PROVISIONING_INTERFACE" ]; then
  # Get rid of any DHCP addresses on the dedicated provisioning interface
  /usr/sbin/ip address flush dev "$PROVISIONING_INTERFACE"

  # Need this to be long enough to bring up the pod with the ip refresh in it.
  # The refresh-static-ip container should lower this back to 10 seconds once it starts.
  # The only time this will actually be set for 5 minutes is if the containers fail to come up.
  /usr/sbin/ip addr add "$PROVISIONING_IP" dev "$PROVISIONING_INTERFACE" valid_lft 300 preferred_lft 300
else
  echo "ERROR: Could not find suitable interface for \"$PROVISIONING_IP\""
  exit 1
fi
