#!/bin/bash

export PGUSER=postgres

pg_databases() {
     echo "SELECT datname FROM pg_catalog.pg_database" | psql -At
}

dbs=$(pg_databases)

mkdir -p /var/backups/pg/
for db in $dbs; do
    if [[ "$db" == "template"* || "$db" == "postgres" ]]; then
        continue
    fi
    for exclude_db in $exclude_dbs; do
        if [ "$exclude_db" == "$db" ]; then
            echo "No backup for database $db as it is listed in 'exclude-dbs'."
            continue 2
        fi
    done
    dst=/var/backups/pg/$db.sql.gz
    (( start = SECONDS ))
    echo "Dumping database $db..." >&2
    pg_dump -Ox "$db" | gzip --rsyncable > "$dst.inprogress"
    errlvl="${PIPESTATUS[0]}"
    ## Atomic replace
    (( elapsed = SECONDS - start ))
    if [ "$errlvl" != "0" ]; then
        echo "  !! Error when dumping database $db." >&2
        rm "$dst.inprogress"
    else
        mv "$dst.inprogress" "$dst"
        printf "  ..dumped %-35s (%12s in %10s)\n" "${dst##*/}" "$(du -sh "$dst" | cut -f 1)" "${elapsed}s" >&2
    fi
done