#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

PREFIX="foocorp"
APP="fooclient"

MONIKER="${PREFIX}-${APP}"
DB="${PREFIX}_${APP}"
DIR="${PREFIX}${APP}"

# Get hostname from mojo config
HOST=$(grep dbi:mysql /srv/deploy_aws_${DIR}/current/${MONIKER}.production.conf | tail -1 | perl -ne'm/host=(.+?);/ && print $1')

# Test connection
mysql -h $HOST --user=$DB --database=$DB --password -e "show tables"

# Actual dump
mysqldump                                      \
    --no-create-db                             \
    --no-tablespaces                           \
    --skip-lock-tables                         \
    --single-transaction                       \
    --complete-insert                          \
    --host=$HOST                               \
    --user=$DB     				               \
    --password                                 \
    --databases $DB                            \
    > ./$DB.dump.$(date +"%Y-%m-%d_%H%M%S").sql

# Explanation
# --no-create-db: prevents "CREATE DATABASE" command
# --no-create-info: Only dumps data, not schema
# --skip-lock-tables: Prevents "Access denied" error
# --single-transaction: Ensures consistent snapshot
# --complete-insert: Specify column names for inserts
# --no-tablespaces: Prevent error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation'