#!/bin/bash
IP=""
NAMESPACE=""
source $(dirname "$(readlink -f "$0")")/variables.sh

help() {
  echo "Usage: $1 <options>"
  echo "       -i : IP to use"
  echo "       -n : Namespace to get ingress information"
  echo "       -k : Kubeconfig to be used"
  echo "       -h : show this help"
  exit 1
}
# Read params
while getopts ":i:n:k:h" opt; do
  case $opt in
    i)
      IP="$OPTARG"
      ;;
    n)
      NAMESPACE="$OPTARG"
      ;;
    k)
      KUBECONFIG="$OPTARG"
      if [ -z "$KUBECONFIG" ]; then
        echo "The variable KUBECONFIG is empty. Using default k8s environment..."
      else
        KUBECONFIG="--kubeconfig $KUBECONFIG"
        echo "The variable KUBECONFIG is not empty. Its value is: $KUBECONFIG"
      fi
      ;;
    h)
      help
      ;;
    \?)
      echo "Not valid option: -$OPTARG" >&2
      help
      ;;
    :)
      echo "The -$OPTARG option requires an argument." >&2
      help
      ;;
  esac
done

if [[ -n "$NAMESPACE" && -n "$IP" ]]
then
  echo "IP: $IP and namespace: $NAMESPACE"
elif [[ -n "$NAMESPACE" ]]; then
  if [[ -n "$K8S_IP" ]]; then
    IP=$K8S_IP
    echo "Using K8S_IP found. IP: $IP and namespace: $NAMESPACE"
  fi
else
  echo "IP ($IP) and NAMESPACE ($NAMESPACE) must be set"
  exit -1
fi


kubectl $KUBECONFIG -n $NAMESPACE get ing|grep -v NAME|awk "{print \"$IP \"\$3}" >> /etc/hosts
