/*********************************************************************
 *
 * This is based on code created by Peter Harvey,
 * (pharvey@codebydesign.com).
 *
 * Modified and extended by Nick Gorham
 * (nick@easysoft.com).
 *
 * Any bugs or problems should be considered the fault of Nick and not
 * Peter.
 *
 * copyright (c) 1999 Nick Gorham
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 **********************************************************************
 *
 * $Id: SQLBrowseConnect.c,v 1.2 1999/12/10 01:50:31 harvey Exp $
 *
 * $Log: SQLBrowseConnect.c,v $
 * Revision 1.2  1999/12/10 01:50:31  harvey
 * Updated with current sources from unixODBC cvs.
 *
 * Revision 1.7  1999/11/13 23:40:58  ngorham
 *
 * Alter the way DM logging works
 * Upgrade the Postgres driver to 6.4.6
 *
 * Revision 1.6  1999/10/24 23:54:17  ngorham
 *
 * First part of the changes to the error reporting
 *
 * Revision 1.5  1999/09/21 22:34:24  ngorham
 *
 * Improve performance by removing unneeded logging calls when logging is
 * disabled
 *
 * Revision 1.4  1999/08/03 21:47:39  shandyb
 * Moving to automake: changed files in DriverManager
 *
 * Revision 1.3  1999/07/10 21:10:15  ngorham
 *
 * Adjust error sqlstate from driver manager, depending on requested
 * version (ODBC2/3)
 *
 * Revision 1.2  1999/07/04 21:05:06  ngorham
 *
 * Add LGPL Headers to code
 *
 * Revision 1.1.1.1  1999/05/29 13:41:05  sShandyb
 * first go at it
 *
 * Revision 1.1.1.1  1999/05/27 18:23:17  pharvey
 * Imported sources
 *
 * Revision 1.2  1999/05/09 23:27:11  nick
 * All the API done now
 *
 * Revision 1.1  1999/04/25 23:02:41  nick
 * Initial revision
 *
 *
 **********************************************************************/

#include "drivermanager.h"

static char const rcsid[]= "$RCSfile: SQLBrowseConnect.c,v $ $Revision: 1.2 $";

#define BUFFER_LEN      4095

SQLRETURN SQLBrowseConnect(
    SQLHDBC            hdbc,
    SQLCHAR            *conn_str_in,
    SQLSMALLINT        len_conn_str_in,
    SQLCHAR            *conn_str_out,
    SQLSMALLINT        conn_str_out_max,
    SQLSMALLINT        *ptr_conn_str_out )
{
    DMHDBC connection = (DMHDBC) hdbc;
    struct con_struct con_struct;
    char *driver, *dsn;
    char lib_name[ INI_MAX_PROPERTY_VALUE + 1 ];
    char driver_name[ INI_MAX_PROPERTY_VALUE + 1 ];
    char in_str[ BUFFER_LEN ];
    SQLRETURN ret;
    SQLCHAR s0[ 20 ], s1[ 100 ], s2[ 100 ];

    /*
     * check connection
     */

    if ( !__validate_dbc( connection ))
    {
        return SQL_INVALID_HANDLE;
    }

    function_entry( connection );

    if ( connection -> log_handle )
    {
        sprintf( connection -> msg, "\n\t\tEntry:\
            \n\t\t\tConnection = %p\
            \n\t\t\tStr In = %s\
            \n\t\t\tStr Out = %s\
            \n\t\t\tPtr Conn Str Out = %p",
                connection,
                __string_with_length( s1, conn_str_in, len_conn_str_in ), 
                __string_with_length( s2, conn_str_out, conn_str_out_max ), 
                ptr_conn_str_out );

        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                connection -> msg );
    }

    /*
     * check the state of the connection
     */

    if ( connection -> state == STATE_C4 ||
        connection -> state == STATE_C5 ||
        connection -> state == STATE_C6 )
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: 08002" );

        __post_internal_error( &connection -> error,
                ERROR_08002, NULL, 
                connection -> environment -> requested_version );
        return function_return( connection, SQL_ERROR );
    }

    /*
     * are we at the start of a connection
     */

    if ( connection -> state == STATE_C2 )
    {
        /*
         * parse the connection string
         */

        __parse_connection_string( &con_struct,
                conn_str_in, len_conn_str_in );

        /*
         * look for some keywords
         * have we got a DRIVER= attribute
         */

        driver = __get_attribute_value( &con_struct, "DRIVER" );
        if ( driver )
        {
            /*
             * look up the driver in the ini file
             */
            SQLGetPrivateProfileString( driver, "Driver", "",
                    lib_name, sizeof( lib_name ), INIDRIVERS );

            if ( lib_name[ 0 ] == '\0' )
            {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: IM002" );

                __post_internal_error( &connection -> error,
                        ERROR_IM002, NULL,
                        connection -> environment -> requested_version );
                __release_conn( &con_struct );
                return function_return( connection, SQL_ERROR );
            }

            sprintf( in_str, "DRIVER={%s};", driver );
            strcpy( connection -> dsn, "" );
        }
        else
        {
            dsn = __get_attribute_value( &con_struct, "DSN" );
            if ( !dsn )
            {
                dsn = "DEFAULT";
            }

            if ( strlen( dsn ) > SQL_MAX_DSN_LENGTH )
            {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: IM012" );

                __post_internal_error( &connection -> error,
                        ERROR_IM012, NULL,
                        connection -> environment -> requested_version );
                return function_return( connection, SQL_ERROR );
            }

            sprintf( in_str, "DSN=%s;", dsn );

            /*
             * look up the dsn in the ini file
             */

            if ( !__find_lib_name( dsn, lib_name, driver_name ))
            {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: IM002" );

                __post_internal_error( &connection -> error,
                        ERROR_IM002, NULL,
                        connection -> environment -> requested_version );
                __release_conn( &con_struct );
                return function_return( connection, SQL_ERROR );
            }

            strcpy( connection -> dsn, dsn );
        }

        __release_conn( &con_struct );

        /*
         * we now have a driver to connect to
         */

        if ( !__connect_part_one( connection, lib_name, driver_name ))
            return function_return( connection, SQL_ERROR );

        if ( !CHECK_SQLBROWSECONNECT( connection ))
        {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: IM001" );

            __disconnect_part_one( connection );
            __post_internal_error( &connection -> error,
                    ERROR_IM001, NULL,
                    connection -> environment -> requested_version );
            return function_return( connection, SQL_ERROR );
        }
    }
    else
    {
        if ( len_conn_str_in == SQL_NTS )
        {
            strcpy( in_str, conn_str_in );
        }
        else
        {
            memcpy( in_str, conn_str_in, len_conn_str_in );
            in_str[ len_conn_str_in + 1 ] = '\0';
        }
    }

    ret = SQLBROWSECONNECT( connection,
            connection -> driver_dbc,
            in_str,
            strlen( in_str ),
            conn_str_out,
            conn_str_out_max,
            ptr_conn_str_out );

    if ( ret == SQL_NEED_DATA )
    {
        connection -> state = STATE_C3;
        return function_return( connection, ret );
    }
    else if ( !SQL_SUCCEEDED( ret ))
    {
        SQLCHAR sqlstate[ 6 ];
        SQLINTEGER native_error, ind;
        SQLCHAR message_text[ SQL_MAX_MESSAGE_LENGTH + 1 ];
        SQLRETURN ret;

        /*
         * get the error from the driver before
         * loseing the connection
         */

        ret = SQLERROR( connection,
                SQL_NULL_HENV,
                connection -> driver_dbc,
                SQL_NULL_HSTMT,
                sqlstate,
                &native_error,
                message_text,
                sizeof( message_text ),
                &ind );

        if ( SQL_SUCCEEDED( ret ))
        {
            __post_internal_error_ex( &connection -> error,
                    sqlstate,
                    native_error,
                    message_text );
        }
        __disconnect_part_one( connection );
        connection -> state = STATE_C1;
    }
    else
    {
        /*
         * we should be connected now
         */

        connection -> state = STATE_C4;
        if ( !__connect_part_two( connection ))
        {
            __disconnect_part_two( connection );
            __disconnect_part_one( connection );
            return function_return( connection, SQL_ERROR );
        }
    }

    if ( connection -> log_handle )
    {
        sprintf( connection -> msg, 
                "\n\t\tExit:[%s]\
                \n\t\t\tPtr Conn Str Out = %s",
                    __get_return_status( ret ),
                    __sptr_as_string( s1, ptr_conn_str_out ));

        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                connection -> msg );
    }

    return function_return( connection, ret );
}
