#!/bin/bash

#
# Copyright (c) 2022 Xibo Signage Ltd
#
# Xibo - Digital Signage - http://www.xibo.org.uk
#
# This file is part of Xibo.
#
# Xibo is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# Xibo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
#

/bin/mkdir -p /var/www/backup/db
age=86401

MYSQL_BACKUP_ENABLED=
MYSQL_DATABASE=

# Is this enabled?
if [ "$MYSQL_BACKUP_ENABLED" == "false" ]
then
  echo "Backup not enabled"
  exit 0
fi

# See if there is an existing backup, and if so, get its age
if [ -e /var/www/backup/db/latest.sql.gz ]
then
    age=$((`date +%s` - `date -r /var/www/backup/db/latest.sql.gz +%s`))

    # Age can potentially be negative. If it is, make it 0 so that
    # we run a backup now
    if [ $age -lt 0 ]
    then
        echo "Last backup was in the future. Resetting"
        age=86401
    fi

    echo "Existing backup is $age seconds old"
fi

# Check if mysqldump is running already
# pgrep exits with 0 if a process is found and 1 otherwise
pgrep mysqldump > /dev/null 2>&1
mysqldump_running=$?

# If the backup is older than 1 day, and mysqldump isn't running,
# then take a new one
if [ $age -gt 86400 ] && [ $mysqldump_running -ne 0 ]
then
    echo "Creating new backup"

    # Tell bash to consider all exit values when evaluating the
    # exit code of a pipe rather than just the right-most one
    # That way we can detect if mysqldump errors or is killed etc
    set -o pipefail

    /usr/bin/mysqldump --single-transaction --hex-blob --no-tablespaces $MYSQL_DATABASE \
      | gzip > /var/www/backup/db/backup.sql.gz

    RESULT=$?

    if [ $RESULT -eq 0 ] && [ -e /var/www/backup/db/backup.sql.gz ]
    then
        echo "Rotating backups"
        mv /var/www/backup/db/latest.sql.gz /var/www/backup/db/previous.sql.gz
        mv /var/www/backup/db/backup.sql.gz /var/www/backup/db/latest.sql.gz
        exit 0
    else
        echo "BACKUP FAILED"
        echo "Not rotating backups"
        exit 1
    fi
elif [ $mysqldump_running -eq 0 ]
then
    echo "Backup already in progress. Exiting"
    exit 0
fi
