#!/bin/bash
# -*- mode: sh; c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil -*-
# vi: set shiftwidth=4 tabstop=8 softtabstop=4 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
# vim: filetype=sh

# ---- error handling
set -o errexit;
set -o posix;
set -o pipefail;
set -o errtrace;
unexpected_error() {
    local errstat=$?
    echo "${g_prog:-$(basename "$0")}: Error! Encountered unexpected error at 'line $(caller)', bailing out..." 1>&2
    exit $errstat;
}
trap unexpected_error ERR;

# Force the path to only what we need, saving off the original path
PATH_ORIG=$PATH;
PATH=/usr/bin:/bin

g_prog=$(basename "$0");
g_progdir=$(dirname "$0");
g_progdir_abs=$(dirname "$(readlink -f "$0")");

# ---- global env

. "$g_progdir_abs/../../private/runtime-common/lib/globalenv.ish"

rootdir_abs="$g_progdir_abs/../.."
g_serverconfigfile="$rootdir_abs/../../userdata/generated/config/smrtlink-system-config.json"

g_python3_exe="$rootdir_abs/bundles/smrttools/smrtcmds/bin/python3"

# ---- main

g_topdir="$g_progdir_abs/../.."

g_exe="$g_topdir/bundles/smrtlink-analysisservices-gui/current/private/thirdparty/postgresql/postgresql_9.6.1/binwrap/psql"

# Read the port and username from the config file, if not specified on the
# command line
got_opt_port=false;
got_opt_username=false;
for opt in ${1+"$@"}; do
    case "$opt" in
        -p|--port) got_opt_port=true;;
        -U|--username) got_opt_username=true;;
    esac
done

psql_opts=()
if [[ -r "$g_serverconfigfile" ]] ; then
    if ! $got_opt_port; then
        port=$("$g_python3_exe" -c "import json; d = json.load(open('$g_serverconfigfile')); print(d['smrtflow']['db']['properties']['portNumber'])")
        psql_opts+=( "--port" "$port" );
    fi
    if ! $got_opt_username; then
        username=$("$g_python3_exe" -c "import json; d = json.load(open('$g_serverconfigfile')); print(d['smrtflow']['db']['properties']['user'])")
        psql_opts+=( "--username" "$username" );
    fi
fi

PAGER=${PAGER:-cat} \
PATH="$PATH" \
   exec "$g_exe" "${psql_opts[@]+${psql_opts[@]}}" ${1+"$@"}
