/*
 * Copyright 2001, 2002, 2003, 2005, 2011, 2013 Adam Sampson <ats@offog.org>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "iolib.h"
#include "freedt.h"
#include "config.h"
const char *progname = "envdir";
const char *proghelp =
	"Usage: envdir [OPTIONS] dir command ...\n"
	"Run a command with environment variables set from a directory.\n\n";

int main(int argc, char **argv) {
	DIR *dir;

	get_default_args(argc, argv);
	if ((argc - optind) < 2)
		help();

	dir = opendir(argv[optind]);
	if (!dir)
		die("unable to open directory");

	while (1) {
		struct dirent *e = readdir(dir);
		buffer filename = BUFFER, value = BUFFER;
		int fd;

		if (!e)
			break;

		if (strcmp(e->d_name, ".") == 0
			|| strcmp(e->d_name, "..") == 0)
			continue;

		bformat(&filename, "@c/@c", argv[optind], e->d_name);

		fd = open(bstr(&filename), O_RDONLY);
		if (fd < 0)
			die2(bstr(&filename), "unable to open file");
		if (readba(fd, &value) < 0)
			die2(bstr(&filename), "read failed");
		
		if (blength(&value) == 0) {
			if (unsetenv(e->d_name) < 0)
				die("unable to unset variable");
		} else {
			const char *s;
			ssize_t pos = bindex(&value, '\n');
			if (pos == -1)
				pos = blength(&value);

			s = bstr(&value);
			while (--pos >= 0) {
				if (s[pos] != ' ' && s[pos] != '\t')
					break;
			}
			bsetlength(&value, pos + 1);

			breplacec(&value, '\0', '\n');

			if (setenv(e->d_name, bstr(&value), 1) < 0)
				die("unable to set variable");
		}
		close(fd);
		bfree(&filename);
		bfree(&value);
	}

	closedir(dir);

	++optind;
	execvp(argv[optind], &argv[optind]);
	die2(argv[optind], "unable to exec");

	return 0; /* NOTREACHED */
}

