/* tabdef - a utility to display a list of fields that a table has, and index info */

#include "tdhkit.h"
#include "shsql.h"

extern int chdir();

int
main( argc, argv )
int argc;
char **argv;
{
int i;
char buf[300];
char tablename[MAXPATH];
char *getenv(), *db;
int stat;
int nf;
char *f[MAXITEMS];
int horizlist;
FILE *fp, *ifp, *popen();
int terse;
int first;
char ixtypestr[255], ixorder[40], ixlevels[40], fieldname[80];

/* process config file.. */
stat = SHSQL_allconfig();
if( stat != 0 ) exit( 1 );


if( argc < 2 ) { 
	printf( "Usage: tabdef [-t] [-h] tablename   .. -t = terse   -h = horizontal\n" ); 
	db = getenv( "SHSQL_DB" );
	if( db == NULL ) db = getenv( "SHSQL_CONFIG" );
	if( db == NULL ) exit(1);
	printf( "Database %s contains these tables:\n", db );
	sprintf( buf, "(cd %s/data; ls)", SHSQL_projdir );
	system( buf );
	exit(1); 
	}

horizlist = 0;
terse = 0;
for( i = 1; i < argc; i++ ) {
	if( strcmp( argv[i], "-h" )==0 ) { horizlist = 1; terse = 1; }
	if( strcmp( argv[i], "-t" )==0 ) terse = 1;
	else strcpy( tablename, argv[i] );
	}

stat = SHSQL_tabdef( tablename, f, &nf );
if( stat != 0 ) goto ERREXIT;
if( !terse ) printf( "'%s' has these fields:\n", tablename );
for( i = 0; i < nf; i++ ) {
	if( !terse ) printf( "%2d. ", i+1 );
	printf( "%s%c", f[i], (horizlist)?' ':'\n' );
	}
if( horizlist )printf( "\n" );

if( nf < 0 ) {
	ERREXIT:
	fprintf( stderr, "%s definition not found in %s/data.  Any similar record defs are shown below:\n", 
		tablename, SHSQL_projdir );
	sprintf( buf, "(cd %s/data; ls %c%c%c*) >&2", SHSQL_projdir, tablename[0], tablename[1], tablename[2] );
	system( buf );
	exit(1);
	}

if( terse ) exit( 0 );

/* print index info */
sprintf( buf, "%s/indexes", SHSQL_projdir );
chdir( buf );
sprintf( buf, "(cd %s/indexes; ls %s.*.2 2>/dev/null)", SHSQL_projdir, tablename );
fp = popen( buf, "r" );
if( fp == NULL ) exit( 1 );
first = 1;
while( fgets( buf, 300, fp ) != NULL ) {
	if( first ) {
		printf( "Indexed fields:\n" );
		first = 0;
		}
	buf[ strlen( buf )-1 ] = '\0';
	ifp = fopen( buf, "r" );
	if( ifp == NULL ) continue;
	fscanf( ifp, "%*s %*s %s %*s %s %*s %s", ixtypestr, ixorder, ixlevels );
	for( i = 0; buf[i] != '\n' && buf[i] != '\0'; i++ ) if( buf[i] == '.' ) buf[i] = ' ';
	sscanf( buf, "%*s %s", fieldname );
	printf( "  %s  (%s,  %s order,  %s levels)\n", fieldname, ixtypestr, ixorder, ixlevels );
	fclose( ifp );
	}
pclose( fp );

if( first ) printf( "No indexes.\n" );


exit( 0 );
}

