#!/bin/bash

# we want to notice when ANY command of a pipe fails (not just the last one)
set -e -u -o pipefail

function error_exit {
    echo "Error: $1" >&2
    exit 1
}

if [[ $# -ne 1 ]]; then
  error_exit "Invalid number of command line arguments"
fi

BACKUP_DIR=${1}
CREDFILE="/root/.my.cnf"

if ! mapfile -t DATABASES < <(mysql "--defaults-extra-file=${CREDFILE}" -Bse 'show databases' | grep -E -v '^(information|performance)_schema$'); then
    error_exit "Could not list databases"
fi

if [ ${#DATABASES[@]} -eq 0 ]; then
    error_exit "No databases found"
fi

DUMP_ERROR=0
for DATABASE in "${DATABASES[@]}"; do
    OPTS=(
        --events
        --routines
        --quick
        --add-locks
        --single-transaction
        --flush-logs
        --no-autocommit
        --ignore-table=mysql.event
    )
    TEMPFILE="$(mktemp -p "${BACKUP_DIR}")"
    if ! mysql "--defaults-extra-file=${CREDFILE}" -Bse "select CONCAT('CREATE OR REPLACE VIEW ', table_name, ' AS ', view_definition, ';') from information_schema.views WHERE table_schema='${DATABASE}';" > "${TEMPFILE}"; then
        DUMP_ERROR=1
        rm -f "${TEMPFILE}"
    else
        if [ -s "${TEMPFILE}" ]; then
            gzip -9 "${TEMPFILE}"
            mv "${TEMPFILE}.gz" "${BACKUP_DIR}/mysql-${DATABASE}.views.sql.gz"
        else
            rm -f "${TEMPFILE}"
        fi
    fi
    mapfile -t VIEWS < <(mysql "--defaults-extra-file=${CREDFILE}" -Bse "select table_name from information_schema.tables where table_schema='${DATABASE}' and table_type like 'view';")
    for VIEW in "${VIEWS[@]}"; do
        OPTS+=(
            --ignore-table="${DATABASE}.${VIEW}"
        )
    done

    TEMPFILE="$(mktemp -p "${BACKUP_DIR}")"
    if ! mysqldump --defaults-extra-file=${CREDFILE} "${OPTS[@]}" "${DATABASE}" | gzip > "${TEMPFILE}"; then
        DUMP_ERROR=1
        rm -f "${TEMPFILE}"
    else
        # Move the dump file atomically.
        # This ensures that the file is not corrupted if multiple
        # dumps run concurrently
        mv "${TEMPFILE}" "${BACKUP_DIR}/mysql-${DATABASE}.sql.gz"
    fi
done

if [ $DUMP_ERROR -ne 0 ]; then
    error_exit "Could not backup all databases"
fi
