#!/usr/bin/env bash

export PATH="$PATH:/snap/bin"

if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit 1;

ELMA365CTL_POD=$(microk8s kubectl get pods --all-namespaces -l app=elma365ctl -o jsonpath='{.items[0].metadata.name}')
PSQL_URL=$(microk8s kubectl get secret elma365-db-connections -o jsonpath='{.data.PSQL_URL}' | base64 -d)
MONGO_URL=$(microk8s kubectl get secret elma365-db-connections -o jsonpath='{.data.MONGO_URL}' | base64 -d)

PSQL_INFO=$(microk8s kubectl exec $ELMA365CTL_POD -n elma365-system -- sh -c "psql $PSQL_URL -c 'SELECT version();' -c 'SELECT * FROM pg_extension;' -c 'SELECT * FROM public.companies;' -c 'SHOW max_connections;' -c 'SHOW work_mem;' -c '\l+' -c '\dt+ *.*'")
MONGO_INFO=$(microk8s kubectl exec $ELMA365CTL_POD -n elma365-system -- sh -c "mongo $MONGO_URL<<"FOO"
show collections

"elma365ctl version"
"hostname -I"
"uname -a"
"cat /etc/os-release"
"free -h"
"snap list"
"df -x overlay -x tmpfs"
"cat /etc/resolv.conf"
"ufw status"
"microk8s kubectl -n argocd get Application"
"microk8s kubectl get all -A"
"microk8s kubectl logs -l tier=elma365 --all-containers | grep '\"fatal\"' "
"microk8s kubectl logs -l tier=elma365 --all-containers | grep '\"error\"' "
"microk8s kubectl logs -l k8s-app=kube-dns -n kube-system"
"microk8s kubectl get cm coredns -n kube-system -o yaml"
"microk8s kubectl logs -l app.kubernetes.io/name=postgresql"
"echo 'Postgres information$PSQL_INFO'>/dev/null"
"echo 'Mongo information $MONGO_INFO'>/dev/null"
"microk8s kubectl logs -l app.kubernetes.io/name=mongodb"
"microk8s kubectl logs -l app=minio"
"microk8s kubectl logs -l app=redis"
"microk8s kubectl get events --all-namespaces"
"microk8s kubectl get nodes"
"microk8s kubectl describe nodes"
"microk8s kubectl describe pods"
"netstat -nlptu"
"ip route"

diagnostic() {
for i in "${COMMANDS[@]}"; do
echo -e "\n=========\n\n# $i\n"
eval $i

toServer() {
diagnostic | curl -X POST --data-binary @- -H 'Authorization:QioZke4_Ijdp' https://nc.elma365.tech

toFile() {
DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"`
diagnostic > $FILENAME
echo -e "Information saved to file ${FILENAME}"


echo -e "\e[93mThis script collect diagnostic information and save it to file or upload to ELMA365 server and generate random link for access to it\e[39m"
echo -e "If you want to upload diagnostic information to server enter S key. For saving to file enter F key"
read -n 1 sf
case $sf in
[Ss]* ) toServer;;
[Ff]* ) toFile;;
* ) echo "exit";;