#!/bin/bash

# This script is inspired by ops_dump.csh. It was originally run on ipp001.
#
# This is the script that performs nebulous databases dumps. It can be run on any
# server hosting the nebulous database. Its main steps are:
# 1) Clean the old dump and the old MD5 checksum files
# 2) Dump the nebulous database
# 3) Computes the MD5 checksum

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

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

HOST=ippdb02

log INFO "Starting nebulous dump"

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

log INFO "Deleting old dumps"
for file in `find $DUMP_PATH -name mysql-neb-$HOST-\*.dump.bz`; do
	log INFO "Deleting $file"
	/bin/rm -f $file
done
DATEVAR=`date +%FT%T`                                   #date        
FILENAME=$DUMP_PATH/mysql-neb-$HOST-$DATEVAR.dump.bz    #dump file name
DB_USERNAME=neb_dump
MD5FILENAME=$DUMP_PATH/neb_checksum.md5

log INFO "Deleting old md5 sum file"
/bin/rm -f $MD5FILENAME

log INFO "Dumping to [$FILENAME]"
/usr/bin/mysqldump -h localhost -u $DB_USERNAME -p$DB_PASSWORD --flush-logs --single-transaction nebulous | ~ipp/local/bin/pbzip2 > $FILENAME
dump_status=${PIPESTATUS[0]}
if [ "$dump_status" -ne "0" ]; then
	log ERROR "Sending warning e-mail"
	email "Nebulous dump failed" $EMAILTO "Check log file: /export/ippdb02.0/mysql-dumps/neb-dump.log"
	log INFO "End of nebulous dump (Error)"
	exit 1
fi

/usr/bin/md5sum $FILENAME > $MD5FILENAME
log INFO "End of nebulous dump (Success)"

