#!/bin/bash
#Developed By: Vaibhav K
# Script: Pull All Logs

PARABLU_CONFIG_SCRIPT_PATH=../../config/parablu_config.sh
PARABLU_COMPONENT_CONFIG_SCRIPT_PATH=../../config/parablu_component_config.sh

source $PARABLU_CONFIG_SCRIPT_PATH
source $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH

BACKBLAZE_ID="14cf87ec3a67"
APPLICATION_KEY="0002e8db9dad3ee8b26c5b02f2c7b50fe760b9d54a"
BACKBLAZE_BUCKET="Mongodbbackups"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
PULLLOGS_CHECK_FILE="get_logs"
dbport=$(grep port: /etc/mongod.conf)
MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')


function get_cust_name ()
{

	CUSTOMER_NAME=$CLOUD_NAME

}

function get_ip_list ()
{

if [ "$SERVER_TYPE" == "3 1" ]; then

echo 'use parablu001
db.PRIVACY_GATEWAY.distinct("gatewayName");' >ipplist.js
else

echo 'use parablu001
db.PRIVACY_GATEWAY.distinct("gatewayName")

db.BLUVAULT.distinct("bluVaultName");' >ipplist.js

fi

        sudo mongo localhost:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < ipplist.js >ipplist.log

        grep '"' ipplist.log | sed -e 's/\[//' | sed -e 's/\]//' | sed -e 's/"//g' | sed -e 's/,//g'  >sorted_ipplist.log
	sed -i "/Implicit/d" sorted_iplist.log
        final_iplist=`cat sorted_ipplist.log`
        OTHER_WATCHDOG_IP=$(echo "$final_iplist" | xargs -n1 | sort -u | xargs)

}

function getOtherServerLogs ()
{

get_ip_list
for ping_ip in ${OTHER_WATCHDOG_IP[@]}
        do
		ssh -p $SSH_PORT $SSH_USERNAME@$ping_ip "zip -r $ping_ip-allLog.zip /parablu/log/"
		sleep 2s
		scp -r -P $SSH_PORT $SSH_USERNAME@$ping_ip:$ping_ip-allLog.zip .
		sleep 2s
		ssh -p $SSH_PORT $SSH_USERNAME@$ping_ip "rm -rf $ping_ip-allLog.zip"
	done

}


###backblaze check

function check_getlogs_backblaze ()
{
	get_cust_name
	backblaze-b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY
	backblaze-b2 ls $BACKBLAZE_BUCKET $CUSTOMER_NAME | grep -oh $PULLLOGS_CHECK_FILE
	if [ $? -eq 0 ]; then
		GET_FILE_VERSION=`backblaze-b2 ls --long $BACKBLAZE_BUCKET $CUSTOMER_NAME  | grep $PULLLOGS_CHECK_FILE | awk '{print $1}' | head -1`
		echo "FILE VERSION: $GET_FILE_VERSION"
		sleep 1s

		zip -r `hostname`-allLog.zip /parablu/log/
		if [ "$SERVER_TYPE" == "3" ]; then
			getOtherServerLogs
		fi
		
		sleep 1s
		zip -r allLogs.zip *.zip
		sleep 2s

		backblaze-b2 upload-file  $BACKBLAZE_BUCKET allLogs.zip $CUSTOMER_NAME/allLogs.zip

		backblaze-b2 delete-file-version $PULLLOGS_CHECK_FILEw $GET_FILE_VERSION

		sleep 4s

		rm -rf *.zip

	fi

}
if [ "$KEY_BASED_SSH" == "true" ]; then
        ssh-agent
        eval $(ssh-agent)
        ssh-add $SSH_KEY_FILE
fi
check_getlogs_backblaze
if [ "$KEY_BASED_SSH" == "true" ]; then
        killall -9 ssh-agent
fi
