#!/bin/bash

# This script is supposed to be executed on ipp001
#
# Its main steps:
# 1) Copies the MD5 checksum from the ithe host where the nebulous db was dumped 
#    using neb_dump.sh
# 2) Copies the nebulous dump
# 3) Checks the copy agaisnt the checksum
# In case of failure, an e-mail is sent to $EMAILTO

. /home/panstarrs/ipp/mysql-dump/functions.sh

EMAILTO=ps-ipp-ops@ifa.hawaii.edu

SOURCE_HOST=ippdb02
HOST=ipp001

SOURCE=ipp@$SOURCE_HOST:/export/$SOURCE_HOST.0/mysql-dumps
TARGET=/export/$HOST.0/ipp/mysql-dumps

MD5FILE=neb_checksum.md5

MAX_ITERATIONS=200
SLEEPING_TIME=60

MD5_COPY_STATUS=1
ITERATION=1
while [ "$MD5_COPY_STATUS" -ne "0" ]; do
	/usr/bin/scp -q $SOURCE/$MD5FILE $TARGET 2> /dev/null
	MD5_COPY_STATUS=$?
	if [ "$MD5_COPY_STATUS" -ne "0" ]; then
		log WARNING "MD5 file not found on $SOURCE_HOST. Waiting $SLEEPING_TIME seconds (Attempt: $ITERATION out of $MAX_ITERATIONS)"
		sleep $SLEEPING_TIME
	else 
		log DEBUG "Checking size of $TARGET/$MD5FILE"
		if [ ! -s $TARGET/$MD5FILE ]; then
			log WARNING "MD5 file has zero-size. Waiting $SLEEPING_TIME seconds (Attempt: $ITERATION out of $MAX_ITERATIONS)"
			MD5_COPY_STATUS=1
			sleep $SLEEPING_TIME
		fi
	fi
	let ITERATION=ITERATION+1
	if [ "$ITERATION" -ge "$MAX_ITERATIONS" ]; then
                log ERROR "Copy of $SOURCE/$MD5FILE failed after $ITERATION iterations. Giving up"
		email "Nebulous MD5 copy failed" $EMAILTO "Copy of $SOURCE/$MD5FILE failed after $ITERATION iterations. Giving up"
		exit 1
	fi
done

log INFO "MD5 file successfully copied ($TARGET/$MD5FILE)"

EXPECTED_MD5SUM=`cat $TARGET/$MD5FILE | sed 's/ .*$//'`
FILE_TO_COPY=`cat $TARGET/$MD5FILE | sed 's/^.* \//\//'`
FILE_TO_COPY=`basename $FILE_TO_COPY`

log INFO "Copying [$FILE_TO_COPY] now (expected MD5 sum: [$EXPECTED_MD5SUM])"
/usr/bin/scp -q $SOURCE/$FILE_TO_COPY $TARGET > /dev/null
if [ "$?" -ne "0" ]; then
	log ERROR "Can't copy nebulous backup file [$FILE_TO_COPY]"
	email "Nebulous backup file [$FILE_TO_COPY] copy failed" $EMAILTO "Can't copy nebulous backup file [$FILE_TO_COPY]"
	exit 2
else
	log INFO "Nebulous backup file [$FILE_TO_COPY] successfully copied"
fi

log INFO "Checking nebulous backup file now"
ACTUAL_MD5SUM=`/usr/bin/md5sum $TARGET/$FILE_TO_COPY | sed 's/ .*$//'`

if [ "$ACTUAL_MD5SUM" != "$EXPECTED_MD5SUM" ]; then
	log ERROR "Checksums are different: actual=[$ACTUAL_MD5SUM], expected=[$EXPECTED_MD5SUM]"
	email "Bad Nebulous checksum" $EMAILTO "Checksums are different: actual=[$ACTUAL_MD5SUM], expected=[$EXPECTED_MD5SUM]"
	exit 3
fi

log INFO "Successfully done with [$TARGET/$FILE_TO_COPY]"

exit 0

