#!/bin/bash

# This script is supposed to be executed on ipp001 (HOST)
#
# It checks, 'installs', and 'distributes' the last gpc1 MySQL dump.
# The main steps are the following:
# 1) Check if a checksum file is available
#    - if it is not, the script sleeps $SLEEPING_TIME seconds, and
#      iterates up to $MAX_ITERATIONS times.
# 2) Check the gpc1 dump file against its checksum.
# 3) Distribute the validated files, that is:
#    - Hard-links the bzipped MySQL dump in the distribution directory
#    - Moves the MD5 checksum to the distribution directory
# 4) Import gpc1 into gpc1_0 or gpc1_1 (ensured by gpc1Import.py utility)
. /home/panstarrs/ipp/mysql-dump/functions.sh

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

HOST=ipp001
TARGET=/export/$HOST.0/ipp/mysql-dumps
MD5FILE=gpc1_checksum.md5

DISTRIBUTION_TARGET=$TARGET/distribution/ippdb01-gpc1.dump.bz
DISTRIBUTION_MD5=$TARGET/distribution/ippdb01-gpc1.md5

MAX_ITERATIONS=200
SLEEPING_TIME=60

log INFO "Starting installation of gpc1"

ITERATION=1
MD5_STATUS=1
while [ "$MD5_STATUS" -ne "0" ]; do
	if [ ! -s $TARGET/$MD5FILE ]; then
		log WARNING "MD5 file not found [$TARGET/$MD5FILE]. Waiting $SLEEPING_TIME seconds (Attempt: $ITERATION out of $MAX_ITERATIONS)"
		sleep $SLEEPING_TIME
		let ITERATION=ITERATION+1
		if [ "$ITERATION" -ge "$MAX_ITERATIONS" ]; then
			log ERROR "Copy of $TARGET/$MD5FILE failed after $ITERATION iterations. Giving up"
			email "Too many failures when attempting to copy $TARGET/$MD5FILE" $EMAILTO "Check log /netdisks/panstarrs/ipp/mysql-dump/gpc1_install.log"
			log INFO "End of gpc1_install.sh (Failure)"
			exit 1
		fi
	else
		MD5_STATUS=0
	fi
done

log INFO "Checking gpc1 backup file checksum"
EXPECTED_MD5SUM=`cat $TARGET/$MD5FILE | sed 's/ .*$//'`
BACKUP_FILE=`cat $TARGET/$MD5FILE | sed 's/^.* \//\//'`
BACKUP_FILE=`basename $BACKUP_FILE`
log INFO "Backup file is [$TARGET/$BACKUP_FILE]"
ACTUAL_MD5SUM=`/usr/bin/md5sum $TARGET/$BACKUP_FILE | sed 's/ .*$//'`
if [ "$ACTUAL_MD5SUM" != "$EXPECTED_MD5SUM" ]; then
        log ERROR "Checksums are different: actual=[$ACTUAL_MD5SUM], expected=[$EXPECTED_MD5SUM]"
	email "Invalid checksum for gpc1 backup" $EMAILTO "Checksums are different: actual=[$ACTUAL_MD5SUM], expected=[$EXPECTED_MD5SUM]"
	log INFO "End of gpc1_install.sh (Failure)"
        exit 2
fi

log INFO "Symlinking backup file [$TARGET/$BACKUP_FILE] to distribution [$DISTRIBUTION_TARGET]"
/usr/bin/ln -f $TARGET/$BACKUP_FILE $DISTRIBUTION_TARGET
/usr/bin/cp -f $TARGET/$MD5FILE $DISTRIBUTION_MD5

# if it is between 0 and 4, ingest into gpc1_0 or gpc1_1
#HOUR=`date +"%H"`
#if [ "$HOUR" -lt "4" ]; then
#	log INFO "Importing gpc1 backup file to gpc1_0 or gpc1_1"
#	/usr/bin/python /home/panstarrs/ipp/mysql-dump/gpc1Import.py
#else
#	log DEBUG "No gpc1 backup importation"
#fi

log INFO "End of gpc1_install.sh (Success)"

