#!/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="$?"
    ## Atomic replace
    (( elapsed = SECONDS - start ))
    if [ "$errlvl" != "0" ]; then
        echo "  !! Error when dumping database $db." >&2
    else
        echo "  ..dumped $db to $dst ($(du -sh "$dst" | cut -f 1) in ${elapsed}s)" >&2
    fi
    mv "$dst.inprogress" "$dst"
done