#!/usr/bin/env bash
##############################################################
#     Script Para Automatizacion De Kraken Console           #
#           Author: Marian Sanchez                           #
##############################################################

if [ -z $1 ] || [ $# -ne 3 ]; then

echo -e "\e[91m PARAMETROS NECESARIOS: nombre_usuario_a_buscar\e[0m"
echo -e "\e[91m MODO DE USO : kraken buscar_usuario 5 nombre_inventario nombre_usuario_a_buscar\e[0m"
exit;

fi

ls /home/kraken/clientes/$1 &> /dev/null

if [ $? -ne 0 ]; then

	echo -e "\e[91m ARCHIVO DE INVENTARIO $1 NO EXISTE EN /home/kraken/clientes/\e[0m"
	exit 1;
	
fi


readarray -t arreglo < /home/kraken/clientes/$1

echo -e "\n"
echo -e "\e[93m ========== BUSQUEDAD USUARIO $2 EN LOS SERVIDORES DEL INVENTARIO: $1 ==============\e[0m"


 for b in ${arreglo[@]}
 do
 
				sshpass -p $3 ssh $b -o StrictHostKeyChecking=no -o ConnectTimeout=5 "exit" &> /dev/null
				
				if [ $? -eq 0 ]; then
 
                sshpass -p $3 ssh $b -o ConnectTimeout=5  -o "StrictHostKeyChecking=no" "cat /etc/passwd | grep $2" &> /dev/null


                if [ $? -eq 0 ]
                then
										
						echo -e "\e[32m $b OK \e[0m"
						echo $b >> /tmp/user5_found

                else
						echo -e "\e[31m $b FAIL \e[0m"
                        echo $b >> /tmp/user5_found_failed

                fi
				
				else
				
						echo $b >> /tmp/user5_found_log
				
				fi

        done


si=$(cat /tmp/user5_found)
no=$(cat /tmp/user5_found_failed)
total_ok=$(cat /tmp/user5_found | wc -l)
acceso=$(cat /tmp/user5_found_log)
cat /tmp/user5_found_failed >> /tmp/user5_found_log
total_nok=$(cat /tmp/user5_found_log | wc -l)
log=$(cat /tmp/search_user5_log)


echo -e "\e[93m ---------------------------------------------------------- \e[0m"
echo -e "\n"

echo -e "\e[32m ========== USUARIO $2 ENCONTRADO EN LOS SERVIDORES ==============\e[0m"
echo -e "\e[32m $si \e[0m"
echo -e "\n"

echo -e "\e[31m ========== USUARIO $2 NO ENCONTRADO EN LOS SERVIDORES ==============\e[0m"
echo -e "\e[31m $no \e[0m"
echo -e "\n"
echo -e "\e[93m Servidores Ok: $total_ok	Servidores Failed: $total_nok   \e[0m"
echo -e "\n\n"
echo -e "\e[31m ========== SERVIDORES CON PROBLEMAS ACCESO (VALIDA PING O CREDENCIALES) ==============\e[0m"
echo -e "\e[31m $acceso \e[0m"
echo -e "\n"
echo -e "\e[93m --------------------- LOGS ------------------------ \e[0m"
echo -e "\e[93m $log \e[0m"
echo -e "\n"


contador=$(cat /tmp/user5_found_failed | wc -l)


rm -f /tmp/search_user5_log &> /dev/null
rm -f /tmp/user5_found &> /dev/null
rm -f /tmp/user5_found_failed &> /dev/null
rm -f /tmp/user5_found_log &> /dev/null


exit 0;

