#!/bin/bash
#
# Version: 2.0

if [ "$1" != "cron" ]; then
  echo "This script is to be run by cron, not manually!"
  exit 1
fi

DB_BACKUP_DIR=/opt/backups/db
DB_BACKUP_KEEP=30

if [ -e /etc/ucs/ucs.conf ]; then
  source /etc/ucs/ucs.conf
fi

if [ -z "$DB_BACKUP_DIR" ]; then
  # Backup is disabled by UCS config.
  exit 0
fi

LOCK=/var/lock/ucs-db-backup

if [ -f $LOCK ]; then
  echo "Previous UCS DB backup seems to be running!"
  echo "Please check running processes and if that is not the case remove $LOCK"
  exit 1
fi

touch $LOCK

if [ ! -d $DB_BACKUP_DIR ]; then
  mkdir -p $DB_BACKUP_DIR
  if [ $? -ne 0 ]; then
    echo "Unable to create backup directory $DB_BACKUP_DIR"
    rm -f $LOCK
    exit 1
  fi
fi

find $DB_BACKUP_DIR -name "*_ucs_*.sql.gz" -mtime +30 -delete

cd $DB_BACKUP_DIR

# We do separate config and data backup so we can get back UCS running faster
# in case of disaster recovery.
yesterday=$(date +%F -d '1 day ago')
/usr/sbin/ucs-db-dump -x ${yesterday}_ucs_config.sql > /dev/null
/usr/sbin/ucs-db-dump -d ${yesterday}_ucs_data.sql > /dev/null
gzip ${yesterday}_ucs_config.sql
gzip ${yesterday}_ucs_data.sql

rm -f $LOCK
