//
// self-test.m
// LGDCommunicationKit Examples, Release 1.0 (prerelease)
//
// Copyright (c) 1993, Looking Glass Design, Inc.
// All rights reserved.
//
// Project Manager:  Paul Girone
// Original Author:  Mike Gobbi
// Creation Date:    June 26, 1993
// $Revision: 1.3 $
//

#import <assert.h>
#import <errno.h>
#import <lgd/commkit/LGDSerialPort.h>
#import <pwd.h>
#import <libc.h>
#import <stdio.h>
#import "test_suite.h"

static LGDSerialPort *port;

void cleanup(void)
{
	printf("\ncleaning up...\n");
	if ([port isOpen]) {
		[port unlockAndClose];
	}
	exit(1);
}

int main(int argc, char *argv[])
{
	char *username;
	char *device = argv[1] ? argv[1] : "cufa";
	int signals[] = {
		SIGINT, SIGQUIT, SIGBUS, SIGSEGV, SIGTERM, 0
	};
	int i;
	int count = 0;
	
	// display instructions
	printf("LGDSerialPort self-test (using device %s)\n", device);
	printf("Press ^C to abort test\n");
	printf("\n");
	
	// check uid
	username = getpwuid(geteuid())->pw_name;
	if (strcmp(username, "root") && strcmp(username, "uucp")) {
		printf("WARNING: %s. %s\n",
			"Not running as root or uucp",
			"Permission errors are likely");
	}
	

	// set ourself up to die nicely no matter what happens
	for (i=0; signals[i]; i++) {
		signal(signals[i], (void *)cleanup);
	}
	
	// create serial port object
	port = [[[LGDSerialPort alloc] init] setDevice:device];
	if (![port isDeviceAvailable:device]) {
		printf("device %s is in use (test not started)\n", device);
		exit(-1);
	}
	
	count += test_locking(port);
	count += test_connecting(port);
	
	[port clearStatus];
	if (![port openAndLockDevice:NULL mode:LGD_SP_CBREAK timeout:15]
	&& ![port status]) {
		printf("open timed out after 15 seconds.  Test aborting.\n");
		exit(1);
	}
	if ([port status]) {
		printf("unexpected error: %s\n", [port statusString]);
		exit(-1);
	}

	count += test_blocks(port);
	count += test_strings(port);
	count += test_characters(port);
	
	count += test_flushing(port);
	count += test_settings(port);
	count += test_signals(port);
	
	[port clearStatus];
	[port unlockAndClose];
	if ([port status]) {
		printf("unexpected error: %s\n", [port statusString]);
		exit(-1);
	}
	
	// free serial port object
	[port free];
	printf("\n%d error%s found overall\n", count, count==1 ? "" : "s");
	return count;
}
