/*
 * main.c :-
 *
 * Turn %-expandos into interesting strings using usernames and other
 * information that usernames get you. Program version....
 *
 * See README for details.
 *
 * $Id: main.c,v 1.2 2002/05/02 16:57:25 dgc Exp $
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <pwd.h>
#include "mailpath.h"

#define LINE_BUF	256

char *A0;

void
usage(void)
{
	fprintf(stderr, "usage: %s [-n] [-f format] [-i input-file] [user]\n", A0);
	fprintf(stderr, "       default format is %s\n", MP_DEFAULT_FMT);
	fprintf(stderr, "       $Id: main.c,v 1.2 2002/05/02 16:57:25 dgc Exp $\n");
}


main(int argc, char *argv[])
{
	char		*fmt, *file, *user, *p;
	int		 uid = MP_NOUID,
			 lkup = MP_LOOKUP,
			 c;
	FILE		*fp;
	char		 buf[LINE_BUF];


	if ((A0 = strrchr(argv[0], '/')) == NULL)
		A0 = argv[0];
	else
		++A0;

	user = MP_NOUSER;
	file = NULL;

	fmt = getenv("MAILPATH_FMT");	/* If NULL, library will handle it. */

	opterr = 0;
	while ((c = getopt(argc, argv, "hnf:i:")) != EOF) {
		switch(c) {
		case 'h':
			usage();
			exit(1);
		case 'n':
			lkup = MP_NOLOOKUP;
			break;
		case 'f':
			fmt = optarg;
			break;
		case 'i':
			file = optarg;
			break;
		default:
			fprintf(stderr, "%s: %c: invalid option\n",
				A0, optopt);
			++opterr;
			break;
		}
	}

	if (opterr || (argc - optind) > 1) {
		usage();
		exit(2);
	}

	if (file) {
		if (!strcmp(file, "-"))
			fp = stdin;
		else
			fp = fopen(file, "r");
		if (fp == NULL) {
			fprintf(stderr, "%s: cannot open file \"%s\": %s\n",
				A0, file, strerror(errno));
			exit(4);
		}
		while (fgets(buf, LINE_BUF-1, fp)) {
			if (p = strchr(buf, '\r'))
				*p = '\0';
			if (p = strchr(buf, '\n'))
				*p = '\0';
			if (p = mailpath(fmt, buf, uid, lkup))
				puts(p);
		}
		if (strcmp(file, "-"))
			fclose(fp);
	} else {
		if ((argc - optind) == 1)
			user = argv[optind];
		if (!user)
			user = getenv("LOGNAME");
		if (!user)
			user = getenv("USER");
		if (!user)
			uid = getuid();

		if (p = mailpath(fmt, user, uid, lkup))
			puts(p);
	}

	exit(0);
}


/*
 * $Log: main.c,v $
 * Revision 1.2  2002/05/02 16:57:25  dgc
 * - Added a syslog() call if compiled with -DDEBUG
 * - Changed main.c to use macros from mailpath.h
 *
 * Revision 1.1  2002/04/23 22:28:27  dgc
 * Separated mailpath.c (core core) and main.c (standalone program).
 * Created README from old comment material. Moved compilation instructions
 * to a Makefile. Added header file; this must be included by client
 * applications.
 *
 * You should install in the usual dev kit fashion:
 * 	.../bin/mailpath
 * 	.../lib/libmailpath.a
 * 	.../include/mailpath.h
 *
 */

