#!/bin/bash

if [[ $# -ne 1 ]] ; then
    echo ""
    echo "Need 1 argument and 1 only (all|cluster_name)"
    echo ""
    exit 1
fi


# require python prettytable 
# require kubectl binaries in /usr/local/bin

# Liste des clusters
# Implique un fichier .kube/config_CLUSTERNAME pour chaque cluster
# Implique un alias go_CLUSTERNAME pour chaque cluster
CLUSTERS=""

temp_https=$(mktemp)
temp_tcp=$(mktemp)
temp_vip=$(mktemp)

if [[ $1 == "all" ]] ; then
    temp_https2=$(mktemp)
    echo "URL Namespace Cluster" >> $temp_https2
    echo "Name Namespace @IP @Port_Name @Port_Number Cluster" >> $temp_tcp
    echo "Name @IP Cluster" >> $temp_vip
    for cluster in $CLUSTERS ; do
        shopt -s expand_aliases
        export KUBECONFIG="~/.kube/config_${cluster}"
        KUBECTL_VERSION=$(grep go_$cluster ~/.bashrc | cut -d "'" -f 2)
        alias kubectl="/usr/local/bin/$KUBECTL_VERSION"
        kubectl get ingress -A --no-headers | awk '{print $4,$1}' | uniq | sed -e "s/$/ $cluster/" >> $temp_https2
        kubectl get svc -A --no-headers -o custom-columns="NAME:.metadata.name,NAMESPACE:.metadata.namespace,IP_ADDRESS:.spec.loadBalancerIP,PORT_NAME:.spec.ports[0].name,PORT_NUMBER:.spec.ports[0].targetPort" --field-selector=metadata.namespace!=ingress-nginx | sed -e "s/$/ $cluster/" | tr -s ' ' | awk '$3 == "<none>" { next } { print }' >> $temp_tcp
        kubectl get svc --no-headers -n ingress-nginx -o custom-columns="NAME:.metadata.name,@IP:.spec.loadBalancerIP" | sed -e "s/$/ $cluster/" | tr -s ' ' | awk '$2 == "<none>" { next } { print }' >> $temp_vip
    done
    sort $temp_https2 > $temp_https
    nb_vip=$(wc -l $temp_vip | cut -d " " -f 1)
    nb_https=$(wc -l $temp_https | cut -d " " -f 1)
    nb_tcp=$(wc -l $temp_tcp | cut -d " " -f 1)
    echo ""
    echo "Found $nb_vip VIPS"
    echo ""
    python3 -c "import sys,prettytable; print(prettytable.from_csv(sys.stdin))" < $temp_vip
    echo ""
    echo "Found $nb_https HTTPS endpoints"
    echo ""
    python3 -c "import sys,prettytable; print(prettytable.from_csv(sys.stdin))" < $temp_https
    echo ""
    echo "Found $nb_tcp TCP VIPS"
    echo ""
    python3 -c "import sys,prettytable; print(prettytable.from_csv(sys.stdin))" < $temp_tcp
    echo ""
    rm -f $temp_https $temp_https2 $temp_tcp $temp_tcp2 $temp_vip
else
    echo "URL Namespace" >> $temp_https
    shopt -s expand_aliases
    export KUBECONFIG="~/.kube/config_${1}"
    KUBECTL_VERSION=$(grep go_${1} ~/.bashrc | cut -d "'" -f 2)
    alias kubectl="/usr/local/bin/$KUBECTL_VERSION"
    echo ""
    if ( ! echo $CLUSTERS | grep -q -w $1 ) ; then
        echo "ERREUR - Le cluster $1 est inconnu"
        echo ""
        exit 1
    fi
    kubectl get ingress -A --no-headers | awk '{print $4,$1}' | uniq | sort >> $temp_https
    echo ""
    python3 -c "import sys,prettytable; print(prettytable.from_csv(sys.stdin))" < $temp_https
    echo ""
    rm -f $temp_https $temp_tcp $temp_vip
fi
