#!/bin/bash

# 參數說明：
# $1: type (prefix / postfix / contain)
# $2: pattern

if [ -z "$2" ]; then
    exec echo "Usage: $0 <type: prefix / postfix / contain> <pattern>"
fi

TYPE=$1
PATTERN=$2

case "${TYPE}" in
    prefix)
        DBNAME_LISTS=$(psql -U postgres -Atqc \
            "SELECT datname FROM pg_database WHERE datname ~ '^${PATTERN}';")
        ;;
    postfix)
        DBNAME_LISTS=$(psql -U postgres -Atqc \
            "SELECT datname FROM pg_database WHERE datname ~ '${PATTERN}$';")
        ;;
    contain)
        DBNAME_LISTS=$(psql -U postgres -Atqc \
            "SELECT datname FROM pg_database WHERE datname ~ '${PATTERN}';")
        ;;
    *)
        echo "Unknown type for ${TYPE}!"
        echo "Valid types: prefix / postfix / contain"
        exit 1
        ;;
esac

for dbname in ${DBNAME_LISTS}; do
    echo "Backup ${dbname}"
    "$HOME/bin/DBbackup" "${dbname}"
done

