/**************************************************
 * SQLConfigDataSource
 *
 * Determine the DriverSetup file name and then try to pass
 * the work along to its ConfigDSN().
 *
 **************************************************
 * This code was created by Peter Harvey @ CodeByDesign.
 * Released under LGPL 28.JAN.99
 *
 * Contributions from...
 * -----------------------------------------------
 * Peter Harvey		- pharvey@codebydesign.com
 **************************************************/
#include <odbcinstext.h>

BOOL SQLConfigDataSource(		HWND	hWnd,
								WORD	nRequest,
								LPCSTR	pszDriver,				/* USER FRIENDLY NAME (not file name) */
								LPCSTR	pszAttributes )
{
	BOOL	(*pFunc)( HWND, WORD, LPCSTR, LPCSTR	);
	BOOL	nReturn;
	void 	*hDLL	= FALSE;
	HINI	hIni;
	char	szDriverSetup[FILENAME_MAX+1];
    char    szIniName[ INI_MAX_OBJECT_NAME + 1 ];


	/* SANITY CHECKS */
	if ( pszDriver == NULL )
	{
		inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );
		return FALSE;
	}
	if ( pszDriver[0] == '\0' )
	{
		inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );
		return FALSE;
	}
	switch ( nRequest )
	{
	case ODBC_ADD_DSN:
	case ODBC_CONFIG_DSN:
	case ODBC_REMOVE_DSN:
	case ODBC_ADD_SYS_DSN:
	case ODBC_CONFIG_SYS_DSN:
	case ODBC_REMOVE_SYS_DSN:
	case ODBC_REMOVE_DEFAULT_DSN:
		break;
	default:
		inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_REQUEST_TYPE, "" );
		return FALSE;
	}

#ifdef SYSTEM_FILE_PATH
    sprintf( szIniName, "%s/odbcinst.ini", SYSTEM_FILE_PATH );
#else
    strcpy( szIniName, "/etc/odbcinst.ini" );
#endif

	/* OK */
	if ( iniOpen( &hIni, szIniName, '#', '[', ']', '=', TRUE ) != INI_SUCCESS )
	{
		inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );
		return FALSE;
	}

	if ( iniPropertySeek( hIni, (char *)pszDriver, "Setup", "" ) == INI_SUCCESS )
	{
   		iniValue( hIni, szDriverSetup );
		iniClose( hIni );

		nReturn = FALSE;
		if ( (hDLL = dlopen( szDriverSetup, RTLD_LAZY ))  )
		{
			pFunc = dlsym( hDLL, "ConfigDSN" );
			if ( dlerror() == NULL )
				nReturn = pFunc( hWnd, nRequest, pszDriver, pszAttributes );
			else
				inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );
			dlclose( hDLL );
		}
		else
			inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );

		return nReturn;

	}

	inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );
	iniClose( hIni );

	return FALSE;
}


