#!/bin/bash
set -e -u -o pipefail

function error_exit {
  echo "Error: $1" >&2
  exit 1
}

if [[ $# -ne 1 ]]; then
  error_exit "Invalid number of command line arguments"
fi

BACKUP_DIR=${1}

SUDO_USER=postgres
BACKUP_FOLDER_OWNER=postgres


if [[ ! -d ${BACKUP_DIR} ]]; then
  mkdir "${BACKUP_DIR:?}" || error_exit "Could not create backup dir"
  chown "${BACKUP_FOLDER_OWNER}":root "${BACKUP_DIR:?}" || error_exit "Could not chown backup dir"
  chmod 0770 "${BACKUP_DIR:?}" || error_exit "Could not chmod backup dir"
fi

FULL_BACKUP_QUERY="SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY datname;"


cd /tmp || exit 1

if ! DATABASES="$(sudo -u $SUDO_USER -E psql -At -c "${FULL_BACKUP_QUERY}" postgres)"; then
  error_exit "Could not list databases"
fi

if [[ -z ${DATABASES} ]]; then
  error_exit "No databases found"
fi

DUMP_ERROR=0
for DATABASE in ${DATABASES}; do
  rm -rf "${BACKUP_DIR:?}/${DATABASE}"
  if ! sudo -u ${SUDO_USER} -E pg_dump -Fd -Z9 -f "${BACKUP_DIR:?}/${DATABASE}" "${DATABASE}"; then
    DUMP_ERROR=1
  fi
  if ! sudo -u ${SUDO_USER} -E pg_dump -Fp -Z9 -f "${BACKUP_DIR:?}/${DATABASE}.sql.gz" "${DATABASE}"; then
    DUMP_ERROR=1
  fi
done

if [[ $DUMP_ERROR -ne 0 ]]; then
  error_exit "Could not backup all databases"
fi
