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

psql_cli=("${psql[@]}")

if [[ ${#psql_cli[@]} -eq 0 ]]; then
    psql_cli=(psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --no-password)
fi

"${psql_cli[@]}" --dbname="$POSTGRES_DB" <<-EOSQL
    CREATE EXTENSION IF NOT EXISTS postgis;
    CREATE EXTENSION IF NOT EXISTS pgcrypto;
EOSQL

existing_db=$("${psql_cli[@]}" --dbname=postgres -tAc "SELECT 1 FROM pg_database WHERE datname = 'railgame_test';")

if [[ "$existing_db" != "1" ]]; then
    "${psql_cli[@]}" --dbname=postgres <<-EOSQL
        CREATE DATABASE railgame_test OWNER ${POSTGRES_USER};
EOSQL
fi

"${psql_cli[@]}" --dbname=railgame_test <<-EOSQL
    CREATE EXTENSION IF NOT EXISTS postgis;
    CREATE EXTENSION IF NOT EXISTS pgcrypto;
EOSQL
