#!/usr/bin/sh
# SITE RUN dump <database>: a compressed mysqldump of one database, on standard output
# The credentials are in a file only the user of uFTP can read: /etc/uftp/mysql-dump.cnf  ([client] user=, password=, host=)
set -eu
database=${1:-}
case "$database" in
    ''|*[!A-Za-z0-9_]*) echo "the database name is letters, digits and _" >&2; exit 2;;
esac
[ "${#database}" -le 64 ] || { echo "the database name is too long" >&2; exit 2; }
MYSQLDUMP=${MYSQLDUMP:-/usr/bin/mysqldump}                     # (a test points it at a stand-in)
CONFIG=${UFTP_MYSQL_CONFIG:-/etc/uftp/mysql-dump.cnf}
[ -r "$CONFIG" ] || { echo "no $CONFIG" >&2; exit 2; }
# the dump goes through a temporary file, so that a failure of mysqldump is a failure of the job (a pipe would hide it)
temporary=$(mktemp "${TMPDIR:-/tmp}/uftp-dump.XXXXXX") || exit 1
trap 'rm -f "$temporary"' EXIT
"$MYSQLDUMP" --defaults-extra-file="$CONFIG" --single-transaction --routines -- "$database" > "$temporary"
gzip -c < "$temporary"
