#include <stdio.h>
#include <syslog.h>
#include <pwd.h>
#include <strings.h>
#include <errno.h>
#include <sys/param.h>
#include <sys/types.h>
#include <time.h>

char *ttyname(), *malloc();
#ifndef ultrix
int strlen();
char *ctime();
#endif

#define LOGFILE "/usr/adm/urban_sql"

#ifdef LOGFILE
#define DO_DATE
#endif

log (cmd, argv)	
char *cmd, *argv[];		
{			
	extern int errno;
	int uid;
	struct passwd *u_pwd;
	char wd[MAXPATHLEN];		/* 1024 */
	char *buffp;
	int i;
	char *tty_id;
	char *cmd_string;
	int cmd_len = 0;
#ifdef LOGFILE
	FILE *f;
#endif
	char	*date_buf = "";
#ifdef DO_DATE
	time_t	clock;
#endif

	if (argv != NULL) {
		for (i = 0; argv[i] != NULL; i++) {
			cmd_len += strlen(argv[i]) + 1;
		}
	}
	getwd(wd);
	uid = getuid();
	u_pwd = getpwuid(uid);
	endpwent();
	tty_id = ttyname(2);
	if (tty_id == NULL) tty_id = "no tty";
	cmd_len += strlen(u_pwd->pw_name) + strlen(wd) + strlen(tty_id) + 6;
	cmd_string = malloc(cmd_len);
	if (cmd_string == NULL) {
		perror("malloc");
		exit(1);
	}

#ifdef DO_DATE
	time(&clock);
	date_buf = ctime(&clock);
	date_buf[20] = '\0';
#endif
	sprintf(cmd_string, "%s%s (%s; %s)", date_buf, u_pwd->pw_name,
		tty_id, wd);
	buffp = cmd_string + strlen(cmd_string);
	while(*argv != NULL) {
		strcpy(buffp++, " ");
		strcpy(buffp, *argv);
		buffp += strlen(*argv++);
	}

#ifdef LOGFILE
	f = fopen(LOGFILE, "a");
	if (f) {
		fprintf(f, "%s\n", cmd_string);
		fclose(f);
	}
#else
	/* syslog() can't handle lines over 1024 chars long... */
	/* This includes ~30 characters of syslog header */
	if (cmd_len > 975)
	     cmd_string[975] = '\0'; /* Let's be on the safe side... */
	syslog(LOG_INFO, "%s", cmd_string);
#endif
}
