#!/bin/bash

m() {
    mysql "${mysql_opts[@]}" -Bs "$@"
}

md() {
    mysqldump "${mysql_opts[@]}" "$@"
}

mysql_databases() {
     echo "SHOW DATABASES" | m
}

mysql_tables() {
    local db="$1"
    echo "SHOW TABLES" | m "$db"
}

mysql_opts=()
if [ "$MYSQLHOST" ]; then
    mysql_opts+=(-h "$MYSQLHOST")
fi


DBS=($(mysql_databases)) || exit 1

mkdir -p /var/backups/mysql

for db in "${DBS[@]}"; do
    if [[ "$db" == "information_schema" || "$db" == "performance_schema" || "$db" == "mysql" ]]; then
        continue
    fi
    echo "Dumping database $db..." >&2
    # omitting all the rotation logic
    dst=/"var/backups/mysql/$db"
    [ -d "$dst.old" ] && rm -rf "$dst.old"
    [ -d "$dst" ] && mv "$dst" "$dst.old"
    mkdir -p "$dst.inprogress"
    (( start = SECONDS ))
    md "$db" --routines --no-data --add-drop-database --database "$db" | gzip --rsyncable > "$dst.inprogress/schema.sql.gz"
    tables=$(mysql_tables "$db")
    for table in $tables; do
        backup_file="$dst.inprogress/${table}.sql.gz"
        echo "  Dumping $table into ${backup_file}"
        md "$db" "$table" | gzip --rsyncable > "$backup_file" || break
    done
    mv "$dst.inprogress" "$dst"
    [ -d "$dst.old" ] && rm -rf "$dst.old"
    (( elapsed = SECONDS - start ))
    echo "  ..dumped $db to $dst ($(du -sh "$dst" | cut -f 1) in ${elapsed}s)" >&2
done