#!/bin/sh
#----------------------------------------------------------------------------
# /var/install/bin/postgresql12-tools-psql - start SQL interpreter
#
# Creation:     2004-07-30 fm
# Last Update:  2023-07-23 09:11:10
#
# Copyright (c) 2024 the eisfair team, team(at)eisfair(dot)org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------

. /var/install/include/eislib
. /etc/config.d/postgresql12

INSTDIR="/usr/lib/pgsql/12/bin"

clrhome
mecho -info "Start SQL interpreter"
echo
echo

{
echo "SELECT d.datname AS \"Name\","
echo "       u.usename AS \"Owner\","
echo "       pg_catalog.pg_encoding_to_char(d.encoding) AS \"Encoding\","
echo "       pg_catalog.obj_description(d.oid, 'pg_database') AS \"Description\""
echo "FROM   pg_catalog.pg_database d"
echo "       LEFT JOIN pg_catalog.pg_user u ON d.datdba = u.usesysid"
echo "ORDER BY 1;"
} | ${INSTDIR}/psql -p "${POSTGRESQL12_CONNECT_PORT}" template1 postgres

echo

echo -e 'database: \c'
read database

if [ "$database" = "" ]
then
    mecho -warn "command cancelled"
    anykey
    exit 0
fi

echo "select usename from pg_user;" | \
    ${INSTDIR}/psql -p "${POSTGRESQL12_CONNECT_PORT}" template1 postgres
echo

echo -e 'Database user [postgres]: \c'
read user

if [ "$user" = "" ]
then
    user=postgres
fi

${INSTDIR}/psql  -p "${POSTGRESQL12_CONNECT_PORT}" -U "$user" "$database"
anykey
exit 0