#!/bin/bash
# DEVELOPER: Vaibhav K

PARABLU_CONFIG_SCRIPT_PATH=../config/parablu_config.sh
PARABLU_COMPONENT_SCRIPT_PATH=../config/parablu_component_config.sh
source $PARABLU_COMPONENT_SCRIPT_PATH
source $PARABLU_CONFIG_SCRIPT_PATH

SCRIPT_PATH=`pwd`
date=`date`
hostname=`hostname`
rm mongooutput.txt
#dbport=$(grep port: /etc/mongod.conf)
#MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')
SUMMARISED_REPORT="/parablu-scripts/Installable/scripts/summary/Backup_Overview_Summary.xlsx"
rm -rf $SUMMARISED_REPORT

dbport=$(grep port: /etc/mongod.conf)
MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')

function exec_mail_ids ()
{

        echo 'use parablu
db.CLOUD_PROPERTIES.find({}).forEach(function(e){print("SUPPORT_MAIL=" +e.supportMail)})' > supportmailids.js

        sudo mongo $DB1_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < supportmailids.js >supportmailid.log

        WATCHDOG_MAIL_ADDRESS=`grep "SUPPORT_MAIL" supportmailid.log | sed -e 's/SUPPORT_MAIL=//' | sed -e 's/,/\ /g'`

        if [[ -z $WATCHDOG_MAIL_ADDRESS ]]; then

                WATCHDOG_MAIL_ADDRESS="support@parablu.com"
        fi
        for mail_id in ${WATCHDOG_MAIL_ADDRESS[@]}
                do
                        MAILARRAY+=({\"email\":\"$mail_id\"},)
        done


        tempids=$(echo -e "${MAILARRAY[*]}")
        get_mail_id=$(echo $tempids | sed -e 's/.$//')

}

function old_exec_summary ()
{
        sudo mongo localhost:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < exec_summary.js >mongooutput.txt
}
function refined_report ()

{
	rm -rf /parablu/bkpOverview/summary
	mkdir -p /parablu/bkpOverview/summary
	mkdir -p summary
	curl -k -X POST https://$BLUVAULT_IP/paracloud/cloud/$CLOUD_NAME/overview/createExcelForScripts/
	sleep 2s
	cp -r /parablu/bkpOverview/Backup_OverviewStatus.xlsx /parablu/bkpOverview/summary/
	if [ "$SERVER_TYPE" == "3" ]; then

		ssh -p $SSH_PORT $SSH_USERNAME@$PARAMAIL_MACHINE "cp /parablu/bkpOverview/Backup_OverviewStatus.xlsx /parablu/bkpOverview/summary/"

	fi
	



}


function new_exec_summary ()
{
        echo -e "" >> mongooutput.txt
        echo -e "*******************************NEW EXECUTIVE SUMMARY**********************" >>mongooutput.txt
	echo -e "CLOUD NAME: $CLOUD_NAME" >>mongooutput.txt
#        nohup java -jar executivesummary-0.0.1-SNAPSHOT.jar &
	nohup java -jar executivesummary-0.0.1-SNAPSHOT.jar --mongodb.parablu.host=$DB_IP --mongodb.parablu001.host=$DB_IP --mongodb.parablu001.port=$MONGODB_PORT --mongodb.parablu.port=$MONGODB_PORT &

        sleep 1m
        #curl -sb -H "Accept: application/json" localhost:8112/overallstatistics >> mongooutput.txt
        curl -sb -H "Accept: application/json" localhost:8112/dashboardstatistics >> mongooutput.txt
        curl -sb -H "Accept: application/json" localhost:8112/userstatistics >> mongooutput.txt
        curl -sb -H "Accept: application/json" localhost:8112/devicestatistics >> mongooutput.txt
        curl -sb -H "Accept: application/json" localhost:8112/deviceoverviewstatistics >> mongooutput.txt
        curl -sb -H "Accept: application/json" localhost:8112/blackListstatistics |& tee -a mongooutput.txt >blacklistmongooutput.txt
	curl -sb -H "Accept: application/json" localhost:8112/o365blackListstatistics |& tee -a mongooutput.txt >o365blacklistmongooutput.txt
	curl -sb -H "Accept: application/json" localhost:8112/bkpOverviewReportStatistics 
        pkill -f executivesummary-0.0.1-SNAPSHOT.jar
        }


function exec_subj_decider ()
{

Last_bkp_perc=`grep  "Last Successful Backup End Time On 7 days" mongooutput.txt | grep -oh [0-9][0-9].[0-9][0-9]% | sed 's/\..*//'`
Last_agent_heard=`grep  "Last Agent heard On 7 days" mongooutput.txt | grep -oh [0-9][0-9].[0-9][0-9]% | sed 's/\..*//'`
Warn_limit='90'


grep "BlackList Users" mongooutput.txt
if [ $? -eq 0 ]; then
	exec_subject="Executive Summary Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] $date- Blacklist Users"
else
		if [[ ${Last_bkp_perc} -gt ${Warn_limit} ]] && [[ ${Last_agent_heard} -gt ${Warn_limit} ]];then

                        exec_subject="Executive Summary Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] $date- Backup is Successful and Agent is talking with Server Successfully"

		elif [[ ${Last_bkp_perc} -lt ${Warn_limit} ]]; then
                        exec_subject="Executive Summary Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] $date- Backup is less than 90%"

		elif [[ ${Last_agent_heard} -lt ${Warn_limit} ]]; then
                        exec_subject="Executive Summary Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] $date- Agent is not talking with Server"
		else
                        exec_subject="Executive Summary Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] $date"
		fi
fi

}

function blukrypt_odb_info ()
{
        echo -e "**************************************************************************" >>mongooutput.txt
#        curl -k -X POST https://$BLUKRYPT_IP/BluKryptBuilder/cloud/$CLOUD_NAME/checkODBFolders

        if [ -f /parablu/reports/odbCheck.log ]; then

                cp -r /parablu/reports/odbCheck.log $SCRIPT_PATH
                cat odbCheck.log |& tee -a mongooutput.txt >odbmongooutput.txt
		sleep 2s
		rm odbCheck.log
		rm  /parablu/reports/odbCheck.log


        fi
        if [ "$SERVER_TYPE" == "3" ] || [ "$SERVER_TYPE" == "3 1" ] || [ "$SERVER_TYPE" == "1" ]; then
                ssh -p $SSH_PORT $SSH_USERNAME@$BLUKRYPT_IP "cp /parablu/reports/odbCheck.log $SCRIPT_PATH  && chmod -R 755 $SCRIPT_PATH/odbCheck.log"
                scp -P $SSH_PORT $SSH_USERNAME@$BLUKRYPT_IP:$SCRIPT_PATH/odbCheck.log .
                cat odbCheck.log |& tee -a mongooutput.txt >odbmongooutput.txt
		sleep 2s
		rm odbCheck.log
                ssh -p $SSH_PORT $SSH_USERNAME@$BLUKRYPT_IP  "cd $SCRIPT_PATH && rm odbCheck.log"

        fi      

#### NEW LOGIC FOR ODB FOLDERS   Uncomment later
#	echo 'use parablu001

#var data = db.ODB_FOLDERS.findOne();
#if(data != null){
#print("Generated on "+data.generatedOn+"\n"+data.folders);
#}else{
#print("No data present in Data base");
#}' > bkodbinfo.js
#          sudo mongo $DB1_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < bkodbinfo.js >odbCheck.log
#          sleep 2s
#          sed -i "/bye/d" odbCheck.log
#sed -i "/switched to/d" odbCheck.log
#sed -i "/MongoDB/d" odbCheck.log
#sed -i "/Implicit session/d" odbCheck.log
#sed -i "/connecting to/d" odbCheck.log
#cat odbCheck.log |& tee -a mongooutput.txt >odbmongooutput.txt
####### END OF NE LOGIC

        echo -e "" >> mongooutput.txt
echo -e "**************************************************************************" >>mongooutput.txt

}

function send_exec_summary_mail ()
{
        exec_mail_ids
	exec_subj_decider

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

		ssh -p $SSH_PORT $SSH_USERNAME@$PARAMAIL_MACHINE "rm -rf /parablu-scripts/Installable/scripts/summary/*"
		ssh -p $SSH_PORT $SSH_USERNAME@$PARAMAIL_MACHINE "cp -r /parablu/bkpOverview/summary/Backup_Overview_Summary.xlsx /parablu-scripts/Installable/scripts/summary"
                ssh -p $SSH_PORT $SSH_USERNAME@$PARAMAIL_MACHINE  "cd $SCRIPT_PATH && rm mongooutput.txt"
                scp -P $SSH_PORT mongooutput.txt $SSH_USERNAME@$PARAMAIL_MACHINE:$SCRIPT_PATH
		ssh -p $SSH_PORT $SSH_USERNAME@$PARAMAIL_MACHINE test  -f "$SCRIPT_PATH/summary/Backup_Overview_Summary.xlsx"

                if [ $? -eq 0 ]; then

			curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyFilePath":"'"${SCRIPT_PATH}/mongooutput.txt"'","subjectData":"'"${exec_subject}"'","recipents":['"${get_mail_id}"'], "attachmentFilePaths":"'"${SUMMARISED_REPORT}"'"}' https://$PARAMAIL_MACHINE/paramail/send/customMail/
		else
                	curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyFilePath":"'"${SCRIPT_PATH}/mongooutput.txt"'","subjectData":"'"${exec_subject}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/
		fi

        else

		cp -r /parablu/bkpOverview/summary/Backup_Overview_Summary.xlsx /parablu-scripts/Installable/scripts/summary
		if [ ! -f $SUMMARISED_REPORT ]
		then
		
                	curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyFilePath":"'"${SCRIPT_PATH}/mongooutput.txt"'","subjectData":"'"${exec_subject}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/
		else
			curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyFilePath":"'"${SCRIPT_PATH}/mongooutput.txt"'","subjectData":"'"${exec_subject}"'","recipents":['"${get_mail_id}"'], "attachmentFilePaths":"'"${SUMMARISED_REPORT}"'"}' https://$PARAMAIL_MACHINE/paramail/send/customMail/
		fi

        fi
}

#### GET GATEWAY NAME AND PG OVERLOAD VALUES

function get_gateway_pg_values ()
{
echo 'use parablu001
db.PRIVACY_GATEWAY.find({}).forEach(function(e){print("GATEWAYNAME=" +e.gatewayName, ":PGLIMIT="+e.componentsProperties.pgOverloadLimit)})' >gateway.js

sudo mongo $DB_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < gateway.js >gateway.log
grep "GATEWAYNAME=" gateway.log >gateway.csv


sleep 5s
}

## MAKING PG OVERLOAD 0
function disabling_incoming ()
{

echo 'use parablu001
db.PRIVACY_GATEWAY.find({}).forEach(function(e){e.componentsProperties.pgOverloadLimit ="0";db.PRIVACY_GATEWAY.save(e);})' >disable_incoming.js

sudo mongo $DB_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < disable_incoming.js

while IFS=":" read -r gateway pgoverload
        do

        GATEWAY=$(echo $gateway | sed -e 's/GATEWAYNAME=//')
        PGOVERLOAD=$(echo $pgoverload | sed -e 's/PGLIMIT=//')
        echo "GATEWAY IS:$GATEWAY "
        echo "PGOVERLOAD IS:$PGOVERLOAD"
        echo "CALL BLUKRYPT API"
        sleep 2s
        curl -k -X POST https://$GATEWAY/BluKryptBuilder/cloud/$CLOUD_NAME/updateProperties/


done < gateway.csv

}

####### ENABLING BACK INCOMING
function enable_incoming ()
{
while IFS=":" read -r gateway pgoverload
        do

GATEWAY=$(echo $gateway | sed -e 's/GATEWAYNAME=//')
PGOVERLOAD=$(echo $pgoverload | sed -e 's/PGLIMIT=//')
echo "GATEWAY IS:$GATEWAY "
echo "PGOVERLOAD IS:$PGOVERLOAD"

echo 'use parablu001

db.PRIVACY_GATEWAY.find({"gatewayName" : "GATEWAY_NAME"}).forEach(function(e) {e.componentsProperties.pgOverloadLimit ="PGOVERLOADLIMIT";db.PRIVACY_GATEWAY.save(e);})' >enable_pglimit.js
sleep 1s
cp enable_pglimit.js install_enable_pglimit.js
sleep 2s
sed -i "s|GATEWAY_NAME|$GATEWAY|g" install_enable_pglimit.js
sed -i "s|PGOVERLOADLIMIT|$PGOVERLOAD|g" install_enable_pglimit.js

sudo mongo $DB_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < install_enable_pglimit.js

sleep 2s
curl -k -X POST https://$GATEWAY/BluKryptBuilder/cloud/$CLOUD_NAME/updateProperties/

        done < gateway.csv
}


function backupstoragelimit_check ()
{

exitCode=$?
maxpercent_val=100
warnpercent_val=80
##GETTING MAIL IDS
exec_mail_ids

java -jar CheckBackupSize.jar $DB_IP $MONGODB_PORT $warnpercent_val https://$PARAMAIL_MACHINE >CheckBackupSize.log
if [[ $exitCode == 0 ]]; then

        grep 'percent=' CheckBackupSize.log
        if [ $? == 0 ]; then
                echo "PERCENT FOUND"
                getperecnt_val=`grep 'percent=' CheckBackupSize.log | sed -e 's/percent=//'`
                echo "PERCENTAGE VAL:$getperecnt_val"

                if [[ $getperecnt_val -ge $warnpercent_val ]] && [[ $getperecnt_val -lt $maxpercent_val ]]; then
                        if [  -f gateway.csv ];then
                                echo "ENABLE INCOMING"
                                enable_incoming
                                mv gateway.csv gateway_old$date_time
                                MSG_SUBJECT="ALERT: Backupstorage Limit Exceed in Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] Machine `hostname` at `date`"
                                MSG_BODY="Incoming Enabled. However Backupstorage limit is still greater than $warnpercent_val Percentage and will be disabled once reaches $maxpercent_val Percentage"

                                curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyData":"'"${MSG_BODY}"'","subjectData":"'"${MSG_SUBJECT}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/
                        else
                                echo "Greater than or equal to $warnpercent_val and less than $maxpercent_val"
                                echo "SEND WARNING MAIL"
                                MSG_SUBJECT="WARNING: Backupstorage Limit Exceed in Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] Machine `hostname` at `date`"
                                MSG_BODY="Backupstorage Limit Exceeded $warnpercent_val Percentage. Incoming will be disabled once the limit reaches $maxpercent_val Percentage"
                                curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyData":"'"${MSG_BODY}"'","subjectData":"'"${MSG_SUBJECT}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/

                        fi
		elif [[ $getperecnt_val -ge $maxpercent_val ]]; then
                        if [  -f gateway.csv ];then
                                echo "ALREADY DISABLED INCOMING"

                                MSG_SUBJECT="ALERT: Backupstorage Limit Exceeded in Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] Machine `hostname` at `date`"
                                MSG_BODY="Backupstorage Limit Exceeded $maxpercent_val Percentage. Incoming Disabled"

                                curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyData":"'"${MSG_BODY}"'","subjectData":"'"${MSG_SUBJECT}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/

                        else
                                echo "Greater  than or equal to $maxpercent_val"
                                echo "Disable PGOVERLOAD"
                                get_gateway_pg_values
                                disabling_incoming
                                MSG_SUBJECT="ALERT: Backupstorage Limit Exceeded in Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] Machine `hostname` at `date`"
                                MSG_BODY="Backupstorage Limit Exceeded $maxpercent_val Percentage. Disabling Incoming"

                                curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyData":"'"${MSG_BODY}"'","subjectData":"'"${MSG_SUBJECT}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/

                        fi
		elif [[ $getperecnt_val -lt $warnpercent_val ]]; then

                        if [  -f gateway.csv ];then
                                echo "ENABLE INCOMING"
                                enable_incoming
                                mv gateway.csv gateway_old$date_time
                                MSG_SUBJECT="ALERT: Backupstorage Limit is fine in Cloud:[$CLOUD_NAME] [$CUSTOMER_NAME] Machine `hostname` at `date`"
                                MSG_BODY="Backupstorage Limit is fine. Incoming Enabled"
                                curl -k -X PUT -H "Content-Type: application/json" -d '{"bodyData":"'"${MSG_BODY}"'","subjectData":"'"${MSG_SUBJECT}"'","recipents":['"${get_mail_id}"']}' https://$PARAMAIL_MACHINE/paramail/send/customMail/

                        else
                                echo "ALL OK....."      
                        fi
                fi
        fi


fi


}

function release_exec_summary ()
{

#        old_exec_summary
	if [ "$PRODUCT_TYPE" == "1 2" ] || [ "$PRODUCT_TYPE" == "2" ]; then
		refined_report
		sleep 2s
		new_exec_summary
		if [ "$STORAGE_TYPE" == "3" ]; then
                        blukrypt_odb_info
                fi
        fi
        send_exec_summary_mail
}

if [ "$MAIN_PARACLOUD" == "true" ]; then
	release_exec_summary
	backupstoragelimit_check
fi
