/*
 * libnqs/misc/machacct.c
 * 
 * DESCRIPTION:
 *
 *	Determine the machine-id of the explicit or implied machine
 *	specification in the given account specification:
 *
 *		account_name			OR
 *		account_name@machine_name
 *
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	November 5, 1985.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <string.h>
#include <netdb.h>			/* Network database */
#include <libnmap/nmap.h>

/*** machacct
 *
 *
 *	int machacct():
 *
 *	Determine the machine-id of the explicit or implied machine
 *	specification in the given account specification:
 *
 *		account_name			OR
 *		account_name@machine_name
 *
 *	Returns:
 *		0: if successful, in which case the machine-id
 *		   parameter is successfully updated as
 *		   appropriate.
 *
 *	       -1: if a null machine-name was specified as
 *		   in:
 *
 *			account_name@
 *
 *	       -2: if the explicit or implied machine-specification
 *		   is not recognized by the local system (NMAP_ENOMAP).
 *
 *	       -3: if the Network Mapping Procedures (NMAP_)
 *		   deny access to the caller (NMAP_ENOPRIV).
 *
 *	       -4: if some other general NMAP_ error occurs.
 */
int machacct (char *account_name, Mid_t *machine_id)
{
	register struct hostent *ent;	/* Host table entry structure */

  	assert(account_name != NULL);
  	assert(machine_id   != NULL);
  
	if ((account_name = strchr (account_name, '@')) == (char *) 0) {
		/*
		 *  No machine-specification was given.  The
		 *  local machine is assumed.
		 */
		return (localmid (machine_id));
	}
	/*
	 *  A machine-name specification appears.
	 */
	account_name++;			/* Step past machine-specification */
					/* introducer character */
	if (*account_name == '\0') {
		/*
		 *  Missing machine-specification.
		 */
		return (-1);		/* Bad syntax */
	}
	/*
	 *  Determine the machine-id of the destination machine.
	 */
	if ((ent = gethostbyname (account_name)) == (struct hostent *) 0) {
		return (-2);		/* This machine is not */
					/* known to us */
	}
	switch (nmap_get_mid (ent, machine_id)) {
	case NMAP_SUCCESS:		/* Successfully got local machine-id */
		return (0);
	case NMAP_ENOMAP:		/* What?  No local mid defined! */
		return (-2);
	case NMAP_ENOPRIV:		/* No privilege */
		return (-3);
	}
	return (-4);			/* General NMAP_ error */
}
