#!/usr/bin/env bash
# @(#) Asks a yes/no question based on an input string (first parameter)
# @(#) - returns exit 1 if user answers no, exit 0 if yes

# Use the unofficial bash strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
# NOTE: requires the `envsubst` tool from the `gettext` GNU package
set -euo pipefail; export FS=$'\n\t'

# we check for existence of table public.client, which means, keycloak database should be initialized
# if no || true, the command will exit here, which lets the container-init fail, resulting in container restart
MYVAR=`psql -U keycloak -d keycloak -c "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'client');" | grep "f" || true`
echo "MYVAR: >${MYVAR}<"
if [ "${MYVAR}" = " f" ] ; then
    echo "initializing default keycloak db"
    psql -U keycloak -d keycloak < /docker-entrypoint-initdb.d/keycloak_db.sql
else
  echo "Database already initialized"
fi
