/*
	SetActive - set active file for use with TIN.

  The environment variable TIN_ACTIVE is set from the file TIN:access
  This file contains a token variable pair on each line. The token can
  either be a username or a user level. The variable is the name of the
  active file for that user. Active files reside in UULIB:

  The contents of the variable matching the user are placed in the local
  environment variable TIN_ACTIVE. UULIB: is prepended to this variable
  name by TIN, so all you need to specify is the filename.

  Access by user level.

  The access file is searched until a token less than or equal to the
  given level is found. If there is no token less than or equal to the
  given level then TIN_ACTIVE is unset. This means that the level tokens
  must be listed in descending order in the access file.

  Access by user name.

  The access file is searched until a token matching the given name is
  found. If there is no token matching the given name then TIN_ACTIVE
  is unset.

  Note that if TIN_ACTIVE is unset, or the file specified does not exist,
  TIN will use UULIB:active as the active file.

  Example using user name:

  ---TIN:access---
# Access file using user names
Tom_Brown luser
Sysop     dude
  ----------------

  1> setactive Tom_Brown
--> TIN_ACTIVE set to luser
  1> setactive Joe_User
--> TIN_ACTIVE not set.

  Example using user level:

  ---TIN:access---
# Access file using user levels
10 dude
5  luser
  ----------------

  1> setactive 15
--> TIN_ACTIVE set to dude
  1> setactive 5
--> TIN_ACTIVE set to luser
  1> setactive 4
--> TIN_ACTIVE not set.

*/

#include <dos/var.h>
#include <stdio.h>

main(argc,argv)
char *argv[];
{
	char *p,str[80];
	int l, lev = -1;
	FILE *fp;

	if (argc != 2)
	{	perror("Usage: SetActive [name|level]\n");
		exit(10);
	}

	DeleteVar("TIN_ACTIVE",GVF_LOCAL_ONLY);

	if (!(fp=fopen("TIN:access","r")))
	{	perror("Can't open TIN:access\n");
		exit(10);
	}
	if (argv[1][0] >= '0' && argv[1][0] <= '9')
	{	lev = atoi(argv[1]);
	}

	for(;;)
	{	fgets(str,80,fp);
		if (feof(fp)) exit(0);
		p = str;
		if (*p=='#' || *p=='\n' || *p == 0) continue;
		
		for (; *p; p++)
		{	if (*p==' ' || *p=='\t')
			{	*p++ = 0;
				for (;*p==' '||*p=='\t';p++);
				break;
			}
		}

		if (lev >= 0)
		{	if (atoi(str) <= lev) break;
		}

		if (stricmp(str,argv[1])==0) break;
	}

	l = strlen(p);
	if (p[l-1] == '\n') p[--l] = 0;

	SetVar("TIN_ACTIVE",(char *)p,(long)(l+1),GVF_LOCAL_ONLY);
	exit(0);
}
