#!/bin/bash
#
# Description: Shell script to backup all MAMP MySQL databases into compressed files
# Script: mamp-db-backup.sh
# Version: 1.0.1
# Script Website: https://gist.github.com/dominicfallows/c1f7bd150f946b7d1dfd1a720a13f8fc
# Author: Dominic Fallows 
# Author Website: https://gist.github.com/dominicfallows
#
# Requirements: 
# - MAMP with MySQL 5.6+
#
# Setup:
# 1) Save your MAMP MySQL root auth details into a config file
# This avoids the "Warning: Using a password on the command line interface can be insecure" error
#
# 2) In terminal, run the following command:
#
# /Applications/MAMP/Library/bin/mysql_config_editor set --login-path=mamp --host=localhost --user=root --password
#
# You will then be asked for your MAMP MySQL password (for root) - default is: root
#
# 3) Make this file executable by running, in terminal, the following command:
#
# chmod +x mamp-db-backup.sh
#
# 4) You can then run this script, in terminal or triggered by an application/scheduler, 
#    from the folder where the file is stored, and you want the databases:
# 
# ./mamp-db-backup.sh
#
# ---------------------------------------------------------------------------------------------------
# CHANGELOG:
#
# Version: 1.0.1
# - Added a --single-transaction flag to prevent errors like:
#   "mysqldump: Got error: 1044: Access denied for user 'root'@'localhost' to database 'information_schema' when using LOCK TABLES" 
#
# Version: 1.0.0
# Launch

if test -f /Applications/MAMP/tmp/mysql/mysql.pid; then
  DB_COUNTER=0
  SECONDS=0

  for db in $(/Applications/MAMP/Library/bin/mysql --login-path=mamp -e 'show databases' -s --skip-column-names); 
    do 
      DB_COUNTER=$[$DB_COUNTER +1] 
      /Applications/MAMP/Library/bin/mysqldump --login-path=mamp --single-transaction "$db" | gzip > "$db.sql.gz"
  done;

  duration=$SECONDS
  echo "$(date) Backed up $DB_COUNTER MAMP MySQL Databases in $duration seconds"

fi;