#!/bin/bash

# Get the PG bin directory path relative to psql caller script.
PG_BIN_PATH=`dirname "$0"`

# If there's an OS supplied version of libreadline, try to make use of it,
# as it's more reliable than libedit, which we link with.
PLL=""

if [ $(uname -m | grep -c 64) = 1 ];
then
    if [ -f /usr/lib64/libreadline.so.6 ];
    then
        PLL=$PLL:/usr/lib64/libreadline.so.6
    fi
    if [ -f /usr/lib64/libreadline.so.5 ];
    then
        PLL=$PLL:/usr/lib64/libreadline.so.5
    fi
    
    if [ -f /lib64/libreadline.so.6 ];
    then
        PLL=$PLL:/lib64/libreadline.so.6
    fi
    if [ -f /lib64/libreadline.so.5 ];
    then
        PLL=$PLL:/lib64/libreadline.so.5
    fi
else
    if [ -f /usr/lib/libreadline.so.6 ];
    then
        PLL=$PLL:/usr/lib/libreadline.so.6
    fi
    if [ -f /usr/lib/libreadline.so.5 ];
    then
        PLL=$PLL:/usr/lib/libreadline.so.5
    fi
    
    if [ -f /lib/libreadline.so.6 ];
    then
        PLL=$PLL:/lib/libreadline.so.6
    fi
    if [ -f /lib/libreadline.so.5 ];
    then
        PLL=$PLL:/lib/libreadline.so.5
    fi
fi


if [ -z "$PLL" ];
then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PG_BIN_PATH/../lib "$PG_BIN_PATH/psql.bin" "$@"
else
	PLL="$PG_BIN_PATH/../lib/libncurses.so.5":"$PLL"
	LD_PRELOAD=$PLL LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PG_BIN_PATH/../lib "$PG_BIN_PATH/psql.bin" "$@"
fi

