#!/bin/bash

source "$(dirname $0)/../dokku_common"
source "$(dirname $0)/../dokku_common_database"

DB_ROOT="$DOKKU_ROOT/.pgsql"
DB_IMAGE="${POSTGRESQL_IMAGE:-ayufan/dokku-alt-postgresql}"
DB_VOLUME="$DB_ROOT/postgresql"
DB_ADMIN_USER="${POSTGRESQL_USER:-root}"
DB_ADMIN_PASSWORD="$DB_ROOT/postgresql_password"
DB_CONTAINER="postgresql_single_container"
DB_CONTAINER_LINK="postgresql"
DB_CONTAINER_VOLUME="${POSTGRESQL_CONTAINER_VOLUME:-/opt/postgresql}"
DB_CONTAINER_PASSWORD="${POSTGRESQL_CONTAINER_PASSWORD:-/opt/postgresql_password}"
DB_HOST="$DB_CONTAINER_LINK"
DB_PORT="${POSTGRESQL_PORT:-5432}"
DB_PROTOCOL="${POSTGRESQL_PROTOCOL:-postgres}"
DB_COMMAND="${POSTGRESQL_COMMAND:-/usr/bin/start_pgsql.sh}"

DB_APP_PASSWORDS="$DB_ROOT/pwd_app_"
DB_APP_DATABASES="$DB_ROOT/dbs_app_"

pgsql_shell() {
  DB_USER="$1"
  DB_PASSWORD="$2"
  shift 2
  ensure_database_container_is_running
  docker run -i --rm \
             --link="$DB_CONTAINER":"$DB_CONTAINER_LINK" \
             -e PGUSER="$DB_USER" \
             -e PGPASSWORD="$(cat "$DB_PASSWORD")" \
             "$DB_IMAGE" \
             bash -c "psql -v ON_ERROR_STOP=1 --host=\"$DB_HOST\" --port=\"$DB_PORT\" $@"
}

pgsql_admin() {
  pgsql_shell "$DB_ADMIN_USER" "$DB_ADMIN_PASSWORD" "--dbname=$DB_ADMIN_USER" "$@"
}
