#!/bin/bash
PATH=/usr/sbin:/usr/bin:/sbin:/bin
DUMP_DATE=$(date +%F-%H%M);
DUMP_CMD="/usr/bin/pg_dump";
DUMP_OPTS="-Fc";
DUMP_DB="metacat";
DUMP_DIR="/var/postgres-bak/";
DUMP_DIR_MONTHS="/var/postgres-bak/months";
DUMP_DIR="/var/postgres-bak/";
DUMP_FILE="metacatDB.${DUMP_DATE}.dump";
DUMP_ERR="metacatDB.${DUMP_DATE}.err";
DUMP_LOG="/var/log/dataone/pgsql-daily-dump.log"
function log() 
{
	#
	# Set Up logging
	# Reminder: don't echo to stdout, it messes up debconf
	#
    now=$(date "+%Y-%m-%d %H:%M:%S %Z: ")
    echo -e "${now} crontab pgsql daily $@" >> ${DUMP_LOG}
}
log "starting"

if [[ ! -d ${DUMP_DIR} ]]; then
  if ! (/bin/mkdir ${DUMP_DIR} >> ${DUMP_LOG} 2>&1); then
    log "/bin/mkdir ${DUMP_DIR} failed"
  fi
  if ! (/bin/chown -R postgres ${DUMP_DIR} >> ${DUMP_LOG} 2>&1); then
    log "/bin/chown -R postgres ${DUMP_DIR}"
  fi
fi

if [[ ! -d ${DUMP_DIR_MONTHS} ]]; then

  if ! (/bin/mkdir ${DUMP_DIR_MONTHS} >> ${DUMP_LOG} 2>&1); then
    log "/bin/mkdir ${DUMP_DIR_MONTHS}"
  fi

  if ! (/bin/chown -R postgres ${DUMP_DIR_MONTHS} >> ${DUMP_LOG} 2>&1); then
    log "/bin/chown -R postgres ${DUMP_DIR_MONTHS}"
  fi

fi

if ! (/usr/bin/find ${DUMP_DIR} -daystart -mtime +31 -regextype posix-extended  -regex "${DUMP_DIR}metacatDB.[0-9]{4}.[0-9]{2}.01.[0-9]{4}.(dump|err)" -exec /bin/mv {} ${DUMP_DIR_MONTHS} \; >> ${DUMP_LOG} 2>&1); then
  log "unable to find and move monthly dumps"
else
  log "found and moved monthly dumps if there were any"
  if ! (/usr/bin/find ${DUMP_DIR} -daystart -mtime +32 -regextype posix-extended  -regex "${DUMP_DIR}metacatDB.[0-9]{4}.[0-9]{2}.[0-9]{2}.[0-9]{4}.(dump|err)" -exec /bin/rm {} \; >> ${DUMP_LOG} 2>&1); then
    log "unable to remove daily dump files"
  fi
fi

nohup su postgres -c "${DUMP_CMD} ${DUMP_OPTS} ${DUMP_DB}" > ${DUMP_DIR}${DUMP_FILE} 2> ${DUMP_DIR}${DUMP_ERR} < /dev/null &

log "completed"