#include "global.h"
#include "commands.h"
#include "register.h"


#if !defined(_lint)
static char rcsid[] OPTIONAL = "$Id: register.c,v 1.12 2000/05/21 22:55:19 gareth Exp $";
#endif

static char *registration;

static int reg_valid (char *str);
static char *reg_version (char *str);
static char *reg_host (char *str);
static void reg_info (void);


int
is_registered ()
{
int retval = 0;

	if (registration && reg_valid (registration))
		retval = 1;
	return (retval);
}


static int
reg_valid (str)
char *str;
{
char *cp;
int val = 0;

	for (cp = str; *cp; cp++)	{
		val += *cp;
	}
	return (!(val % 256));
}

#define REG_VERS_OFFSET 1
#define REG_HOST_OFFSET 20

static char *
reg_version (str)
char *str;
{
static char vers[5];

	if (!reg_valid (str) || (strlen (str) < REG_VERS_OFFSET + 4))
		strcpy (vers, "???");
	else
		sprintf (vers, "%c.%c%c", str[REG_VERS_OFFSET] - '#' + '0',
			str[REG_VERS_OFFSET + 1] - '#' + '0',
			str[REG_VERS_OFFSET + 2] - '#' + '0');
	return vers;
}


static char *
reg_host (str)
char *str;
{
static char host[32], *cp;
int k, len;

	if (!reg_valid (str) || (strlen (str) < REG_HOST_OFFSET))
		strcpy (host, "unknown host");
	else {
		len = str[REG_HOST_OFFSET] - 'a';
		if ((int)strlen (str) < (REG_HOST_OFFSET + len + 1))
			strcpy (host, "unknown host");
		else {
			for (k = 0,cp = host; k < len; k++, cp++)
				*cp = str[REG_HOST_OFFSET + 1 + k] - 1;
			*cp = 0;
		}
	}
	return host;
}



static void
reg_info ()
{
	tprintf ("copy of TNOS registered to %s since release %s\n",
		reg_host (registration),
		reg_version (registration));
}

void
reg_status ()
{
	if (!registration)
		registration = strdup (REGISTRATION);

	if (!strcmp (registration, "unregistered"))	{
#if 0
		tputs ("*** Running an unregistered copy of TNOS "VERSION"\n");
#else
		return;
#endif
	} else {
		if (!reg_valid (registration))
			tputs ("*** Running invalid ");
		else
			tputs ("*** This ");
		reg_info ();
	}
}


int
doregister (argc, argv, p)
int argc;
char *argv[];
void *p OPTIONAL;
{
	if (argc == 1)	{	/* viewing registration info */
		if (!registration)
			registration = strdup (REGISTRATION);
		tprintf ("Registration: %s\n", registration);
		if (strcmp (registration, "unregistered"))	{
			tputs ("This ");
			reg_info ();
			return 0;
		}
	} else 			/* setting registartion info */
		registration = strdup (argv[1]);
	return 0;
}


int
doregistry (argc, argv, p)
int argc OPTIONAL;
char *argv[] OPTIONAL;
void *p OPTIONAL;
{
	if (!registration)
		registration = strdup (REGISTRATION);
	if (strcmp (registration, "unregistered")) {
		tputs ("This ");
		reg_info ();
	}
#if 0
	else
		tputs ("This copy of TNOS is unregistered\n");
#endif
	return 0;
}


#ifdef TEST
void
main (argc, argv)
int argc;
char *argv[];
{
	if (argc != 2)
		exit (1);
	printf ("Registration valid = %d\n", reg_valid (argv[1]));
	printf ("Registered release = %s\n", reg_version (argv[1]));
	printf ("Registered hostname = %s\n", reg_host (argv[1]));
}

#endif /* TEST */
