#!/bin/bash

[ ! -z "$PSQL_LIB_UTIL" ] && return 0
PSQL_LIB_UTIL=true

# Source the abstract library first and override its definitions below.
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/db "db"


function _is_postgresql_server_running() {
    pgepopt="-h $OPENSHIFT_POSTGRESQL_DB_HOST -p $OPENSHIFT_POSTGRESQL_DB_PORT"
    pguseropt="-U $OPENSHIFT_POSTGRESQL_DB_USERNAME"

    PGPASSWORD="$OPENSHIFT_POSTGRESQL_DB_PASSWORD"   \
        /usr/bin/psql $pgepopt $pguseropt -l > /dev/null 2>&1  &&  return 0
    return 1
}


function wait_to_start_db {
    i=0
    while ( _is_postgresql_server_running || [ ! -f ${CART_INSTANCE_DIR}/pid/postgres.pid ]) && [ $i -lt 10 ]
    do
        sleep 1
        i=$(($i + 1))
    done
}


function wait_to_start_db_as_user {
    ttw=60  #  Time (max) to wait for db to start up.
    if [ -n "$OPENSHIFT_POSTGRESQL_DB_USERNAME" ]
    then
        i=0
        sleep 1
        while ( ! _is_postgresql_server_running ) && [ $i -lt $ttw ]
        do
            sleep 1
            i=$(($i + 1))
        done
    fi
}


function prepare_gear_for_standalone_postgresql() {
    # Find an open localhost IP
    PROXY_IP=`find_open_ip $uid $uuid`

    # Add apache vhost configuration.
    create_standard_path_env_var
    import_env_vars
    $CART_INFO_DIR/bin/deploy_httpd_proxy.sh $application $namespace $uuid $PROXY_IP

    disable_stale_detection

    restart_httpd_graceful
}
