#!/usr/bin/env bash
#
# Backup local MySQL Database tables with a certain prefix.
# Ismo Vuorinen <https://github.com/ivuorinen> 2018
# License: MIT

set -euo pipefail

# Enable verbosity with VERBOSE=1
VERBOSE="${VERBOSE:-0}"
# Default database
DEFAULT_DATABASE="wordpress"

# Function to print usage information
usage()
{
  echo "(>) Usage: $SCRIPT <TABLE_PREFIX> <FILENAME_PREFIX> [<DATABASE>]"
  echo " * <TABLE_PREFIX>    = database table prefix, e.g. 'wp_'"
  echo " * <FILENAME_PREFIX> = FILENAME prefix, defaults to table prefix. Use something descriptive e.g. 'wordpress'"
  echo " * <DATABASE>        = [optional] Third argument DATABASE, defaults to '$DEFAULT_DATABASE'."
  exit 1
}

# Function to print messages if VERBOSE is enabled
# $1 - message (string)
msg()
{
  [[ "$VERBOSE" -eq 1 ]] && echo "$1"
}

# Function to print error messages and exit
# $1 - error message (string)
msg_err()
{
  echo "(!) ERROR: $1" >&2
  exit 1
}

# Function to backup MySQL tables with a certain prefix
# $1 - table prefix (string)
# $2 - filename prefix (string)
# $3 - database name (string)
backup_mysql_tables()
{
  local prefix=$1
  local filename=$2
  local database=$3

  local timestamp
  timestamp=$(date "+%Y%m%d_%H%M%S")
  local filename_timestamp="${database}_${filename}_${timestamp}.sql"

  msg "Backing up tables with prefix '$prefix' from database '$database' to file '$filename_timestamp'"

  mysqldump \
    "${database}" \
    "$(
      echo "show tables like '${prefix}%';" \
        | mysql "${database}" \
        | sed '/Tables_in/d'
    )" > "${filename_timestamp}"

  msg "Backup completed and saved to '$filename_timestamp'"
}

# Main function
main()
{
  if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
    usage
  fi

  local prefix=$1
  local filename=$2
  local database=${3:-$DEFAULT_DATABASE}

  if [ -z "$prefix" ]; then
    msg_err "TABLE_PREFIX (first argument) is missing"
  fi

  if [ -z "$filename" ]; then
    filename=$prefix
  fi

  backup_mysql_tables "$prefix" "$filename" "$database"
}

# Script name for usage information
SCRIPT=$(basename "$0")

main "$@"
