#include "captive.h"


/* See captive_adduser.c for info.  This program just reads all the records into
   an array, sorts them by username, then prints them.  */




int main( int argc, char *argv[]) {

	GDBM_FILE dbf;
	datum key, nextkey;
	datum content;

	int count;
	int i, j, done;
	char tmpbuffer[20];
	time_t tp;

	char     user_name[1000][USERNAME_LEN];
	userinfo user_info[1000];
	char	temp[USERNAME_LEN];

	dbf = gdbm_open( "/var/smoothwall/mods/captive/captivedb", 512, GDBM_READER, S_IRWXU, NULL );

	count = 0;
	key = gdbm_firstkey ( dbf );
	if( key.dptr != NULL ) key.dptr[key.dsize] = '\0';   /* Add null term, just to be safe. */
	while ( key.dptr ) {

		content = gdbm_fetch( dbf, key );

		strncpy( user_name[count], key.dptr, key.dsize );
		user_info[count] = *(userinfo *)content.dptr;

		count++;

		free ( content.dptr );
		nextkey = gdbm_nextkey ( dbf, key );

       		free ( key.dptr );
		key = nextkey;
		if( key.dptr != NULL ) key.dptr[key.dsize] = '\0';   /* Add null term, just to be safe. */
	}

	done = 0;


	while( !done ) {
		done = 1;
		for( i = 0; i < count-1; i++ ) {
			if( strncmp(user_name[i],user_name[i+1],USERNAME_LEN) > 0 ) {
				strncpy( temp, user_name[i], USERNAME_LEN );
				strncpy( user_name[i], user_name[i+1], USERNAME_LEN );
				strncpy( user_name[i+1], temp, USERNAME_LEN );
				userinfoswap( &user_info[i], &user_info[i+1] );
				done = 0;
			}
		}
	}


	time( &tp );
	for( i = 0; i < count; i++ ) {
		printf( "  %s", user_name[i] );
		for( j = 0; j < (USERNAME_LEN-strlen(user_name[i])); j++ ) printf( " " );
		printf( "%s", user_info[i].password );
		for( j = 0; j < (PASSWORD_LEN-strlen(user_info[i].password)); j++ ) printf( " " );
		snprintf( tmpbuffer, 20, "%.1f hours", ((float)user_info[i].login_dur_in_seconds/3600.0) );
		printf( "%s", tmpbuffer );
		for( j = 0; j < (12-strlen(tmpbuffer)); j++ ) printf( " " );
		if( user_info[i].enabled == 0 ) printf( "disabled    " );
		else if( user_info[i].enabled == 2 ) printf( "one-time    " );
		else printf( "            " );
		if( user_info[i].logged_in_now )
			printf( "Logged in at %s (%s).  Expires in %s.\n", user_info[i].ip, user_info[i].mac, timeleftstring(user_info[i].login_expires_at-(long)tp) );
		else printf( "\n" );
	}

	gdbm_close( dbf );

	return 0;
}
