/*
 * Copyright 1998-2002 Ben Smithurst <ben@smithurst.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * list files under ~/mail
 */

static const char rcsid[] =
	"$BCPS: src/mailutils/mail-ls.c,v 1.4 2002/12/30 22:41:14 ben Exp $";

#include "misc.h"

void usage(void);
void check_file(char *);
void get_maxlen(char *);

#define SIG_EXIT() {				\
	warnx("exiting because of signal");	\
	exit(1);				\
	}

size_t maxlen;

int
main(int argc, char *argv[]) {
	int ch;
	TREE *tree = NULL;

	while ((ch = getopt(argc, argv, "")) != -1)
		usage();

	argc -= optind;
	argv += optind;

	if (argc == 0)
		files_to_tree(&tree, mailpath());
	else
		array_to_tree(&tree, argv);

	check_tree(tree, get_maxlen);
	check_tree(tree, check_file);
	return (0);
}

void
get_maxlen(char *file) {
	size_t len = strlen(print_mailbox(file));

	if (len > maxlen)
		maxlen = len;
}

static const char *
get_type(char *file) {
	int fd;
	char buf[5];

	if (is_maildir(file))
		return ("Maildir");

	if ((fd = open(file, O_RDONLY)) < 0)
		return ("-");
	switch (read(fd, buf, 5)) {
	case 0:
		close(fd);
		return ("empty");
	case 5:
		if (memcmp(buf, "From ", 5) == 0) {
			close(fd);
			return ("MBOX");
		}
		/* FALLTHROUGH */
	default:
		close(fd);
		return ("-");
	}
}

void
check_file(char *file) {
	const char *type;
	int size;

	size = mailbox_size(file, NULL);
	type = get_type(file);
	printf("%-*s %-8s %8d\n", maxlen, print_mailbox(file), type, size);
}

void
usage(void) {
	fprintf(stderr, "usage: mail-ls [file ...]\n");
	exit(EX_USAGE);
}


syntax highlighted by Code2HTML, v. 0.9.1