#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <svrapi.h>
#pragma hdrstop

#pragma comment( lib, "svrapi.lib" )


void DisplaySessions( const char *server )
{
	char *buf;
	int bufsize, level, successLevel;
	session_info_10 *cur10;
	session_info_50 *cur50;
	DWORD rc, i;
	WORD read, total;

	buf = NULL;
	successLevel = 90;

	// try levels 10 and 50 in this order, until we don't get a level error
	for ( rc = ERROR_INVALID_LEVEL, level = 10;
		rc == ERROR_INVALID_LEVEL && level <= 50; level += 40 )
	{
		bufsize = 1024;
		do
		{
			printf( "Trying: level %d, bufsize = %d bytes\n", level, bufsize );
			if ( buf != NULL )
				free( buf );
			buf = (char *) malloc( bufsize );

			// NOTE: pre-Jul98 Platform SDKs had bugs in the headers
			// and required a cast for the first three args (to char*).

			rc = NetSessionEnum( server, level, buf, bufsize, &read, &total );

			if ( rc == 0 )
				successLevel = level;

			bufsize += 1024;
		} while ( bufsize < 65536 && ( rc == ERROR_MORE_DATA || rc == ERROR_INVALID_PARAMETER ) );
	}

	if ( rc != ERROR_SUCCESS )
	{
		printf( "NSE() returned %lu\n", rc );
		exit( 1 );
	}

	// belts and braces
	if ( successLevel != 10 && successLevel != 50 )
	{
		printf( "why is successLevel == %d?\n", successLevel );
		exit( 1 );
	}

	printf( "%-30.30s %-30.30s %-8.8s\n", "Client", "User", "Idle sec" );
	printf( "%-30.30s %-30.30s %-8.8s\n", "------------------------------",
		"------------------------------", "--------" );

	switch ( successLevel )
	{
		case 10:
			for ( i = 0, cur10 = (session_info_10 *) buf; i < read; ++ i, ++ cur10 )
			{
				printf( "%-30.30s %-30.30s %02d:%02d:%02d\n",
					cur10->sesi10_cname == NULL? "": cur10->sesi10_cname,
					cur10->sesi10_username == NULL? "": cur10->sesi10_username,
					cur10->sesi10_time / 3600, ( cur10->sesi10_time % 3600 ) / 60,
					cur10->sesi10_time % 60 );
			}
			break;
		case 50:
			for ( i = 0, cur50 = (session_info_50 *) buf; i < read; ++ i, ++ cur50 )
			{
				printf( "%-30.30s %-30.30s %02d:%02d:%02d\n",
					cur50->sesi50_cname == NULL? "": cur50->sesi50_cname,
					cur50->sesi50_username == NULL? "": cur50->sesi50_username,
					cur50->sesi50_time / 3600, ( cur50->sesi50_time % 3600 ) / 60,
					cur50->sesi50_time % 60 );
			}
			break;
		default:
			printf( "why is successLevel == %d, and why didn't the "
				"earlier \"if\" catch it?\n", successLevel );
			exit( 1 );
			break;
	}
}



int main( int argc, char *argv[] )
{
	const char *server = NULL;

	if ( argc > 2 )
	{
		puts( "\nnsesse95 [\\\\server]\n" );
		puts( "\\\\server -- machine to check, with backslashes, please." );
		puts( "  Default: local machine.\n" );
		return 1;
	}

	if ( argc > 1 )
		server = argv[1];

	DisplaySessions( server );

	return 0;
}

