#!/bin/bash

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

source $PARABLU_CONFIG_SCRIPT_PATH 2> /dev/null
source $PARABLU_COMPONENT_SCRIPT_PATH

BACKBLAZE_ID="14cf87ec3a67"
APPLICATION_KEY="00066055d8f4b83d31775758b2f06f06f9cfd04baf"
BACKBLAZE_BUCKET="Mongodbbackups"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
#CUSTOMER_NAME="Vktest"
date_time="`date '+%Y%m%d'`.zip"
SCRIPT_PATH=`pwd`


function get_cust_name ()
{
        custname=$(grep "CUSTOMER_NAME=" /var/lib/parablusys/bin/scripts/mongo_full_backup.sh)
        CUSTOMER_NAME=$(echo $custname | tr -d ' ' | sed -e 's/CUSTOMER_NAME=//' | sed 's/"//g')

}

function check_patch_backblaze ()
{
	get_cust_name
	b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY

	b2 ls $BACKBLAZE_BUCKET $CUSTOMER_NAME | grep -oh UpgradeServer-$date_time
	if [ $? -eq 0 ]; then
        	GET_FILE_NAME=`b2 ls $BACKBLAZE_BUCKET $CUSTOMER_NAME | grep -oh UpgradeServer-$date_time`

	        echo "NEW SERVER UPDATE AVAILABLE : $GET_FILE_NAME"
        	b2 download-file-by-name $BACKBLAZE_BUCKET $CUSTOMER_NAME/UpgradeServer-$date_time UpgradeServer-$date_time
	        if [ $? -eq 0 ]; then

			echo "SERVER UPDATE DOWNLOADED SUCCESSFULLY"
		else
			echo "DOWNLOAD FAILED FROM BACKBLAZE"
			exit
	        fi

	else
        	echo "NO NEW SERVER UPDATES AVAILABLE"
		exit
	fi

}

function patch_distribute ()
{
	for each_ip in ${OTHER_WATCHDOG_IP[@]}
        	do
                	scp -P $SSH_PORT UpgradeServer-$date_time $SSH_USERNAME@$each_ip:$SCRIPT_PATH/
                done
}

function start_server_upgrade ()
{

	if [ -f UpgradeServer-$date_time ]; then
		unzip -o UpgradeServer-$date_time
        	sleep 2s
	        bash UpgradeServer.sh

		sleep 5s
		rm UpgradeServer-$date_time
		rm UpgradeServer.sh
		rm -rf read_input*
	fi
}

if [ "$SERVER_TYPE" == "0" ]; then
	check_patch_backblaze
	start_server_upgrade
elif [ "$SERVER_TYPE" == "3" ]; then
	check_patch_backblaze
	patch_distribute
	start_server_upgrade
else
	sleep 2m
	start_server_upgrade
fi
