#!/bin/sh
# SITE RUN dump <database>: a compressed pg_dump of one database, on standard output
# The credentials are in a service file only the user of uFTP can read: /etc/uftp/pg_service.conf, a [uftp] section (host, user, password)
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 63 ] || { echo "the database name is too long" >&2; exit 2; }
PGDUMP=${PGDUMP:-/usr/bin/pg_dump}                             # (a test points it at a stand-in)
PGSERVICEFILE=${UFTP_PG_SERVICEFILE:-/etc/uftp/pg_service.conf}
export PGSERVICEFILE
[ -r "$PGSERVICEFILE" ] || { echo "no $PGSERVICEFILE" >&2; exit 2; }
temporary=$(mktemp "${TMPDIR:-/tmp}/uftp-dump.XXXXXX") || exit 1
trap 'rm -f "$temporary"' EXIT
PGSERVICE=uftp "$PGDUMP" --no-password --dbname="$database" > "$temporary"
gzip -c < "$temporary"
