/*
 *	Code ripped out of login.c to get location.
 *	Will not work for remote login, which sets location
 *	to name of calling machine, which is passed to login
 *	as an argument. Ho hum.
 *
 *	Martin Guy, November 1987
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <loc.h>

#define	TMPFILE		"/etc/loctmp"

extern	struct ttyb	*loctty();
extern	char		*rindex();

extern	int	errno;

main(argc, argv)
int argc;
char *argv[];
{
	struct ttyb *ttybp;
	char *progname;
	int t;

	progname = rindex(argv[0], '/');
	if (progname == NULL)
		progname = argv[0];
	else
		progname += 1;

	/*
	 * Get the location of this terminal.
	 * This probably won't work for remote logins.
	 */
	ttybp = loctty(1);

	if (progname[0] != 'u') {
		int count;
		char *extrap = ttybp->t_extra;
		int space = T_EXTRAL - 1;

		/*
		 * User wants to change the location,
		 * either to a new one, or to nothing at all.
		 */

		/*
		 * Copy the first argument into the location buffer.
		 * If there is no argument, it will be NULL.
		 */
		(void) strncpy(ttybp->t_name, argv[1], LN_NAMEL);

		/*
		 * Copy all arguments after the first into
		 * the "extra" location buffer, with spaces
		 * in between them. This code is awful.
		 */
		for (count = 2; count < argc && space > 0; count++) {
			char *ap = argv[count];

			while (space-- > 0 && *ap != '\0')
			       *extrap++ = *ap++;
			if (space-- > 0)
				*extrap++ = ' ';
		}
		*extrap = '\0';
	}

	/*
	 * Write the location record into the loctmp file.
	 */
	t = ttyslot();
	if (t > 0) {
		int f;

		f = open(TMPFILE, 1);

		/*
		 * If it failed because it doesn't exist, create it.
		 */
		if (f < 0 && errno == ENOENT)
			f = creat(TMPFILE, 0644);
		if (f >= 0) {
			lseek(f, (long) (t * sizeof(*ttybp)), 0);
			write(f, (char *) ttybp, sizeof(*ttybp));
			close(f);
		}
	}

	exit(0);
}

