/*
 * locktest - test portlib file-locking functions
 *
 * This program tries to acquire a lock.  If the lock is obtained
 * successfully, the program sleeps for 10 seconds, then releases
 * the lock.  To use the program, start one instance, then start
 * another before the first releases the lock.  The first instance
 * should get the lock, the second instance should fail.  When the
 * first instance exits, start a third instance.  The first instance
 * should successfully acquire a lock.
 *
 * Options:
 * -s n		sleep for n seconds instead of default 10
 * -f name	create file with given name instead of default "lock.test"
 *
 * 29 November 1996
 * Paul DuBois
 * dubois@primate.wisc.edu
 * http://www.primate.wisc.edu/people/dubois/
 */

#include	<stdio.h>

#include	"portlib.h"


#ifndef bufSiz
#define bufSiz 1024
#endif

static char	lockFile[bufSiz] = "lock.test";
static int	sleepTime = 10;
static char	*usage = "Usage: locktest [ -s sleeptime ] [ -f lockfile ]";

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

	--argc;			/* skip program name */
	++argv;
	while (argc > 0 && argv[0][0] == '-')
	{
		if (strcmp (argv[0], "-s") == 0)
		{
			if (argc < 2)
			{
				fprintf (stderr, "%s\n", usage);
				exit (1);
			}
			sleepTime = StrToInt (argv[1]);
			argc -= 2;
			argv += 2;
		}
		else if (strcmp (argv[0], "-f") == 0)
		{
			if (argc < 2)
			{
				fprintf (stderr, "%s\n", usage);
				exit (1);
			}
			(void) strcpy (lockFile, argv[1]);
			argc -= 2;
			argv += 2;
		}
		else
		{
			fprintf (stderr, "unknown option: %s\n", argv[0]);
			fprintf (stderr, "%s\n", usage);
			exit (1);
		}
	}
	if (argc != 0)
	{
		fprintf (stderr, "%s\n", usage);
		exit (1);
	}
	printf ("opening \"%s\" file\n", lockFile);
	/*
	 * Create file if it doesn't exist, but if it does exist,
	 * don't overwrite the contents.  We just want to lock it,
	 * not destroy it.
	 */
	if ((f = fopen (lockFile, "a+")) == (FILE *) NULL)
	{
		printf ("could not open \"%s\", exiting\n", lockFile);
		exit (1);
	}
	printf ("trying to acquire lock\n");
	if (AcquireLock (f) == 0)
	{
		printf ("lock not acquired, exiting\n");
		(void) fclose (f);
		exit (1);
	}
	printf ("lock acquired successfully\n");
	sleep (sleepTime);
	printf ("releasing lock\n");
	ReleaseLock (f);
	(void) fclose (f);
	exit (0);
}
