#!/bin/bash

CLUSTERS=""
temp=$(mktemp)
temp2=$(mktemp)
temp3=$(mktemp)

echo "DB;Type;Version;Namespace;Cluster" > $temp

for cluster in $CLUSTERS ; do
        shopt -s expand_aliases
        export KUBECONFIG="/slashroot/home/jarchina/.kube/config_${cluster}"
        KUBECTL_VERSION=$(grep go_$cluster ~/.bashrc | cut -d "'" -f 2)
        alias kubectl="/usr/local/bin/$KUBECTL_VERSION"
        #kubectl get pods -A -no-headers -o custom-columns="NAME:.metadata.name,IMAGE:.spec.containers[0].image,NAMESPACE:.metadata.namespace" | grep -v kube-fledged | grep -E 'mysql:|mariadb:|postgresql:' | sed -e "s/$/ $cluster/" | tr -s ' ' >> $temp2
        kubectl get deploy,sts -A -o custom-columns="NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image,NAMESPACE:.metadata.namespace" | grep -v kube-fledged | grep -E 'mysql:|mariadb:|postgresql:' | sed -e "s/$/ $cluster/" | tr -s ' ' > $temp2
        while read line ; do
            db=$(echo $line | cut -d " " -f 1)
            image_name=$(echo $line | cut -d " " -f 2 | awk -F "/" '{print $NF}' | cut -d ":" -f 1)
            image_version=$(echo $line | cut -d " " -f 2 | cut -d ":" -f 2)
            ns=$(echo $line | cut -d " " -f 3)
            cluster=$(echo $line | cut -d " " -f 4)
            echo "$db;$image_name;$image_version;$ns;$cluster" >> $temp3
        done < $temp2
done

total=$(wc -l $temp3 | cut -d " " -f 1)
sort $temp3 -t ";" -k 2,3 >> $temp
echo ""
echo "Found $total DBs"
echo ""

python3 -c "import sys,prettytable; print(prettytable.from_csv(sys.stdin))" < $temp

rm -f $temp $temp2 $temp3

