#!/bin/bash
PARABLU_CONFIG_SCRIPT_PATH=/parablu-scripts/Installable/config/parablu_config.sh
PARABLU_COMPONENT_SCRIPT_PATH=/parablu-scripts/Installable/config/parablu_component_config.sh
source $PARABLU_CONFIG_SCRIPT_PATH
source $PARABLU_COMPONENT_SCRIPT_PATH
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"

# Functions
setVariables () {

	# Username to access the mongo server e.g. dbuser. Unnecessary if authentication is off
	DBUSERNAME="neil"

	# Password to access the mongo server e.g. password. Unnecessary if authentication is off
	DBPASSWORD="parablu"

	# Database for authentication to the mongo server e.g. admin. Unnecessary if authentication is off
	DBAUTHDB="admin"

	# Host name (or IP address) of mongo server e.g localhost
	DBHOST="$1" 

	# Port that mongo is listening on
	DBPORT="27017"

	# Backup directory location e.g /backups
	BACKUPDIR="/parablu/backup/mongodb"

	#Archive Directory
        ARCHIVEDIR="/parablu/archive/mongodb_backup"

	# Allow DBUSERNAME without DBAUTHDB
	REQUIREDBAUTHDB="no"

	# OPT string for use with mongodump
	OPT=""                                            

	# Use oplog for point-in-time snapshotting.
	OPLOG="no"

	# External DB Backup
        EXTERNAL_bACKUP="no"

        # External DB Backup Path
        EXTERNAL_DB_PATH="/parablu/PROD_CENTRAL_BACKUP/MONGO_BACKUPS/"

        # External DB SSh User
        EXTERNAL_DB_SSH_USER="root"

        # External DB IP
        EXTERNAL_DB_IP="192.168.144.4"

        # External DB Port
        EXTERNAL_DB_SSH_PORT="22"
	
	BACKBLAZE_ID="14cf87ec3a67"

        APPLICATION_KEY="00066055d8f4b83d31775758b2f06f06f9cfd04baf"

        BACKBLAZE_BUCKET="Mongodbbackups"

	CUSTOMER_NAME="ParabluTest"

        BACKBLAZE_BACKUP="no"

	ENCRYPT_BACKUP="yes"

	ENCRYPT_PASSPHRASE="$CUSTOMER_NAME-@#*7#87^t"

        MONGO_ZIP_FILE="$CUSTOMER_NAME-`date '+%Y%m%d'`.zip"

	MONGO_ENCRYPTED_FILE="$CUSTOMER_NAME-`date '+%Y%m%d'`.gpg"

	# Do we need to use a username/password?
	if [ "$DBUSERNAME" ]; then
    		OPT="$OPT --username=$DBUSERNAME --password=$DBPASSWORD"
    		if [ "$REQUIREDBAUTHDB" = "yes" ]; then
        		OPT="$OPT --authenticationDatabase=$DBAUTHDB"
    		fi
	fi

	# Do we use oplog for point-in-time snapshotting?
	if [ "$OPLOG" = "yes" ]; then
    		OPT="$OPT --oplog"
	fi
}

function send_backpfail_alert ()
{

##Get mail ids
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/.$//')

                MSG_SUBJECT="ALERT: MONGO BACKUP FAILURE [$CUSTOMER_NAME] Machine `hostname` at `date`"
                MSG_BODY="MONGO BACKUP FAILED"
                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/


}

# Database dump function
dbdump () {
	setVariables "localhost"
	echo
	echo Backup of Database Server - on $DBHOST 
	echo ======================================================================

	echo Backup Start `date`
	echo ======================================================================

	mkdir -p $BACKUPDIR
	mkdir -p $ARCHIVEDIR
	FOLDER=$BACKUPDIR/`date '+%Y%m%d'`
	rm -rf $FOLDER
    	mongodump --host=$DBHOST:$DBPORT --out=$FOLDER $OPT 
	if [ $? -ne 0 ] ; then
                echo "MongoDump Failed" >> /parablu/mongo_backup_status
                send_backpfail_alert
                return 0
        fi
    	if [ ! -e "$FOLDER" ] ; then 
		echo "MongoDump Failed" >> /parablu/mongo_backup_status
		return 0
	fi
	echo ----------------------------------------------------------------------
	echo Backup End Time `date`
	echo ======================================================================
	echo "MONGO BACKUP 
LAST BACKEDUP FILE : "$BACKUPDIR/$MONGO_ZIP_FILE" 
LAST BACKEDUP DATE: `date`" >> /parablu/mongo_backup_status
	zip -r $BACKUPDIR/$MONGO_ZIP_FILE $FOLDER
	sleep 2s
        rm -rf $FOLDER
    	cd $BACKUPDIR
        echo "Moving old Backups to archive...."
        for i in `find . -mtime +1`; do
                echo -e "Archiving Backup Folder $i";
                mv $i $ARCHIVEDIR
                #tar -cf $ARCHIVEDIR/$i.tar -C $ARCHIVEDIR $i;
                #rm -rf $ARCHIVEDIR/$i
        done
        cd $ARCHIVEDIR
        ls -t | find . -mtime +3 | xargs -d '\n' rm
	if [ "$EXTERNAL_bACKUP" = "yes" ]; then
                ssh -p $EXTERNAL_DB_SSH_PORT $EXTERNAL_DB_SSH_USER@$EXTERNAL_DB_IP "mkdir -p $EXTERNAL_DB_PATH"
                scp -r $FOLDER $EXTERNAL_DB_SSH_USER@$EXTERNAL_DB_IP:$EXTERNAL_DB_PATH
        fi
	if [ "$BACKBLAZE_BACKUP" = "yes" ]; then
                if [ "$ENCRYPT_BACKUP" = "yes" ]; then

                 #       zip -r $MONGO_ZIP_FILE $FOLDER
                        gpg -c --batch --passphrase $ENCRYPT_PASSPHRASE -o $MONGO_ENCRYPTED_FILE $BACKUPDIR/$MONGO_ZIP_FILE
                        b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY
                        b2 upload-file  $BACKBLAZE_BUCKET $MONGO_ENCRYPTED_FILE $CUSTOMER_NAME/$MONGO_ENCRYPTED_FILE
			if [ $? -ne 0 ]; then
				sleep 20s
				b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY
				b2 upload-file  $BACKBLAZE_BUCKET $MONGO_ENCRYPTED_FILE $CUSTOMER_NAME/$MONGO_ENCRYPTED_FILE
			fi

                else
                  #      zip -r $MONGO_ZIP_FILE $FOLDER
                        b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY
                        b2 upload-file  $BACKBLAZE_BUCKET $BACKUPDIR/$MONGO_ZIP_FILE $CUSTOMER_NAME/$MONGO_ZIP_FILE
			if [ $? -ne 0 ]; then
				sleep 20s
				b2 authorize-account $BACKBLAZE_ID $APPLICATION_KEY
	                        b2 upload-file  $BACKBLAZE_BUCKET $BACKUPDIR/$MONGO_ZIP_FILE $CUSTOMER_NAME/$MONGO_ZIP_FILE
			fi
                fi

		sleep 2s
                rm -rf $MONGO_ZIP_FILE
		rm -rf $MONGO_ENCRYPTED_FILE
		rm -rf $ARCHIVEDIR/*
        fi
    	return 1
}

rm -rf /parablu/mongo_backup_status*
dbdump 

exit $STATUS
