#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) {
fdt_unsetenv(e->d_name);
} else {
const char *s;
int 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 (fdt_setenv(e->d_name, bstr(&value)) < 0)
die("unable to set variable");
}
close(fd);
bfree(&filename);
bfree(&value);
}
++optind;
execvp(argv[optind], &argv[optind]);
die2(argv[optind], "unable to exec");
return 0; /* NOTREACHED */
}
syntax highlighted by Code2HTML, v. 0.9.1