#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.0.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Drop database in Postgres Docker container.'
    echo "Syntax: $script [-c|help]"
    echo 'Example: $script -c postgres01 -d odoo'
    echo 'options:'
    echo "  -c    Docker container. Defaults to 'postgres'."
    echo '  -d    Comma-separated list of database names.'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

container=postgres

while getopts ":c: :d:" opt; do
  case $opt in
    c) container="$OPTARG";;
    d) database="$OPTARG";;
    \?) echo "Invalid option -$OPTARG" >&2
    help
    exit 1;;
  esac
done

[[ -z "$database" ]] && { echo 'Parameter -d|database is empty.' ; exit 1; }

docker_exec_bash="docker exec $container /bin/bash -c"

echo "Checking if database '$database' exists..."
db_exists=$($docker_exec_bash "psql postgresql://\$POSTGRES_USER:\$POSTGRES_PASSWORD@\$HOSTNAME/postgres -tAc \"SELECT 1 FROM pg_database WHERE datname='$database';\"" 2>/dev/null | grep -q 1 && echo "True" || echo "False")
if [[ "$db_exists" == "False" ]]; then
    echo "Database '$database' does not exist. Nothing to drop."
    exit 0
fi

echo 'Kill all database connections'
query="SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$database';"
$docker_exec_bash "psql postgres://\$POSTGRES_USER:\$POSTGRES_PASSWORD@\$HOSTNAME:5432/postgres -c \"$query\""

echo "Drop Postgres database $database on container $container ..."
$docker_exec_bash "psql postgresql://\$POSTGRES_USER:\$POSTGRES_PASSWORD@\$HOSTNAME/postgres -tAc 'DROP DATABASE \"$database\";'"
