#!/usr/bin/env bash
# configure.sh - configure test environment after cluster install.
#
# Sets PATH to include the bz-provisioned bin dir, exports external-node
# credentials when external_ip and external_key files exist in BZ_LOCAL_DIR
# (written by bz install or gkm), propagates IPAM test config, and applies
# the optional failsafe patch.
#
# Required env:
#   BZ_LOCAL_DIR
# Optional env:
#   IPAM_TEST_POOL_SUBNET, FAILSAFE_443, K8S_E2E_DOCKER_EXTRA_FLAGS
#
# Exports consumed by later phases:
#   PATH, EXT_USER, EXT_IP, EXT_KEY, K8S_E2E_DOCKER_EXTRA_FLAGS
#
# Sourced from body_*.sh.

if [[ -z "${BZ_LOCAL_DIR}" ]]; then echo "[ERROR] BZ_LOCAL_DIR is required but not set"; exit 1; fi

export PATH=$PATH:${BZ_LOCAL_DIR}/bin

if [[ -f "${BZ_LOCAL_DIR}/external_ip" ]] && [[ -f "${BZ_LOCAL_DIR}/external_key" ]]; then
  export EXT_USER=ubuntu
  EXT_IP=$(cat "${BZ_LOCAL_DIR}/external_ip")
  export EXT_IP
  export EXT_KEY=${BZ_LOCAL_DIR}/external_key
  export K8S_E2E_DOCKER_EXTRA_FLAGS="-v $EXT_KEY:/key --env EXT_USER --env EXT_KEY=/key --env EXT_IP $K8S_E2E_DOCKER_EXTRA_FLAGS"
  echo "EXT_USER=ubuntu EXT_IP=$EXT_IP, EXT_KEY=$EXT_KEY"
  echo "K8S_E2E_DOCKER_EXTRA_FLAGS=$K8S_E2E_DOCKER_EXTRA_FLAGS"
fi

if [ -n "${IPAM_TEST_POOL_SUBNET}" ]; then
  export K8S_E2E_DOCKER_EXTRA_FLAGS="$K8S_E2E_DOCKER_EXTRA_FLAGS --env IPAM_TEST_POOL_SUBNET"
  echo "IPAM_TEST_POOL_SUBNET=$IPAM_TEST_POOL_SUBNET"
fi

# Some pipelines (e.g., VPP) need port 443 added to the failsafe outbound rules
# so nodes can reach the kube-apiserver. This replaces the default failsafe list
# with one that includes 443. TODO: consider making 443 a default failsafe port
# so this patch isn't needed.
if [ "${FAILSAFE_443}" == "true" ]; then
  KUBECONFIG=${BZ_LOCAL_DIR}/kubeconfig kubectl patch felixconfiguration default --type=merge \
    -p '{"spec":{"failsafeOutboundHostPorts": [{"protocol": "udp", "port":53},{"protocol": "udp", "port":67},{"protocol": "tcp", "port":179},{"protocol": "tcp", "port":2379},{"protocol": "tcp", "port":2380},{"protocol": "tcp", "port":5473},{"protocol": "tcp", "port":443},{"protocol": "tcp", "port":6666},{"protocol": "tcp", "port":6667}]}}'
fi
