#!/bin/bash

# This script is based on ops_dump.csh. It was originally run on ipp001. I changed it a bit
#
# Now it is supposed to be run on $HOST where a MySQL server hosts the gpc1 database (it can
# the master or one of its slaves). It performs the following tasks:
# 1) It tidies up the local directory used for MySQL dumps, namely:
#       - it deletes the old MySQL dumps
#       - it deletes the old MD5 checksum file
# 2) It calls mysqldump to dump gpc1 to some bzipped file
# 3) It computes the checksum
# 4) It copies the dump and the checksum files onto the TARGET_HOST

# Load utilities functions
. /home/panstarrs/ipp/mysql-dump/functions.sh
. /home/panstarrs/ipp/mysql-dump/password.sh

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

HOST=ippc02
TARGET_HOST=ipp0012
TARGET_DIR=/export/ipp001.0/ipp/mysql-dumps/

log INFO "Starting gpc1 backup"

DUMP_PATH=/export/$HOST.0/mysql-dumps                  #path

#1) Cleaning
log INFO "Deleting old dumps"
for file in `find $DUMP_PATH -name mysql-gpc1-$HOST-\*.dump.bz`; do
	log INFO "Deleting $file"
	/bin/rm -f $file
done
log INFO "Deleting old md5 sum file"
/bin/rm -f $MD5FILENAME

#2) Dumping
DATEVAR=`date +%FT%T`                                   #date        
FILENAME=$DUMP_PATH/mysql-gpc1-$HOST-$DATEVAR.dump.bz    #dump file name
DB_USERNAME=gpc1_dump
MD5FILENAME=$DUMP_PATH/gpc1_checksum.md5
log INFO "Dumping to $FILENAME"
/usr/bin/mysqldump -h localhost -u $DB_USERNAME -p$DB_PASSWORD --flush-logs --single-transaction gpc1 | ~ipp/local/bin/pbzip2 > $FILENAME
dump_status=${PIPESTATUS[0]}
if [ "$dump_status" -ne "0" ]; then
	log ERROR "Sending warning e-mail"
	email "Gpc1 dump failed" $EMAILTO "Check log file: /export/$HOST.0/mysql-dumps/gpc1_dump.log"
	log INFO "End of gpc1 dump (Error)"
	exit 1
fi

#3) Checksum
log INFO "Generating MD5 checksum"
/usr/bin/md5sum $FILENAME > $MD5FILENAME
log INFO "End of gpc1 dump (Success)"

#4) Copy onto TARGET_HOST
log INFO "Copying $FILENAME on $TARGET_HOST"
sudo -u ipp /usr/bin/scp -q $FILENAME ipp@$TARGET_HOST:$TARGET_DIR
log INFO "Copying MD5 checksum file to $TARGET_HOST"
sudo -u ipp /usr/bin/scp -q $MD5FILENAME ipp@$TARGET_HOST:$TARGET_DIR

log INFO "End of gpc1 backup (Success)"

