/* "If it's fast on Linux, great.  If it works on other OSes, that's a bonus"
   -- Andrew Tridgell 
*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>

#include "ccontrol.h"

struct config config =
{
	.num_prefixes = 0,
	.argv_subbed = 0,
	.verbose = 0,
	.num_compiles_offset = 0,
	.num_parallel = 0,
};

static int parse_verbose(unsigned int pos, const char *value)
{
	config.verbose = 1;
	return 1;
}

static int parse_num_compiles(unsigned int pos, const char *value)
{
	config.num_compiles = strtoul(value, NULL, 16);
	config.num_compiles_offset = pos;
	return 1;
}

static int parse_prefix(unsigned int pos, const char *value)
{
	char **newargv;

	newargv = malloc(sizeof(config.argv[0]) * (config.argc+2));

	/* Insert at end of prefixes. */
	memcpy(newargv, config.argv, sizeof(char *) * config.num_prefixes);
	newargv[config.num_prefixes] = (char *)value;
	/* Copy original cmdline incl. NULL at end of argv */
	memcpy(newargv + config.num_prefixes + 1,
	       config.argv + config.num_prefixes,
	       sizeof(char *) * (config.argc + 1 - config.num_prefixes));

	config.argv = newargv;
	config.argc++;
	config.num_prefixes++;
	return 1;
}

static int parse_env(unsigned int pos, const char *value)
{
	char *eq, *val;

	val = strdup(value);
	eq = strchr(val, '=');

	if (!eq)
		return 0;
	*eq = '\0';
	setenv(val, eq + 1, 1);
	return 1;
}

static int parse_cleanenv(unsigned int pos, const char *value)
{
	char *env, *i;

	for (env = environ[0]; *env; env++) {
		/* If it starts with this prefix, remove from env. */
		if (strncmp(env, value, strlen(value)) == 0) {
			for (i = env; *i; i++)
				*i = *(i+1);
		}
	}
	return 1;
}

static int parse_niceness(unsigned int pos, const char *value)
{
	if (config.verbose)
		printf("ccontrol: setting nice level to %i\n", atoi(value));
	setpriority(PRIO_PROCESS, 0, atoi(value));
	return 1;
}

static int parse_numlimit(unsigned int pos, const char *value)
{
	config.num_parallel = atoi(value);
	return 1;
}

static int parse_autolimit(unsigned int pos, const char *value)
{
	config.autolimit = atoi(value);
	return 1;
}
#include "ccontrol_hash.c"

static int is_wrapper(const char *fname)
{
	int len;
	char linkname[PATH_MAX+1];

	len = readlink(fname, linkname, sizeof(linkname));
	if (len > 0) {
		char *start;
		linkname[len] = '\0';
		start = strrchr(linkname, '/');
		if (!start) start = linkname;
		else start++;
		if (streq(start, "ccontrol")
		    || streq(start, "distcc")
		    || streq(start, "ccache"))
			return 1;
	}
	return 0;
}

static void do_compile(const char *compiler, char*argv[])
{
	char *i, *path;

	if (strrchr(compiler, '/'))
		compiler = strrchr(compiler, '/')+1;

	path = strdup(getenv("PATH") ?: "");

	for (i = strtok(path,":"); i; i = strtok(NULL, ":")) {
		char *fname;

		asprintf(&fname, "%s/%s", i, compiler);
		/* Check we're not going to exec ourselves! */
		if (!is_wrapper(fname)) {
			execv(fname, argv);
			if (config.verbose && errno != ENOENT)
				fprintf(stderr,
					"ccontrol: can't exec %s: %s\n", 
					fname, strerror(errno));
		}
	}
}

static void __attribute__((noreturn)) __too_hard(char *argv[], int line)
{
	if (config.verbose)
		fprintf(stderr, "ccontrol: %s too hard at %u\n",
			argv[0], line);
	do_compile(argv[0], argv);
	exit(1);
}

#define too_hard(argv) __too_hard((argv), __LINE__)

static int lock_fd(int fd)
{
	struct flock fl;

again:
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 1;
	fl.l_pid = 0;

	if (fcntl(fd, F_SETLKW, &fl) < 0) {
		if (errno == EINTR)
			goto again;
		return 0;
	}
	return 1;
}

static char *suck_file(int fd)
{
	char *contents;
	int r, done = 0, len = 4096;

	contents = malloc(len + 1);
more:
	r = read(fd, contents + done, len - done);
	if (r < 0)
		return NULL;
	done += r;
	if (r == 0) {
		contents[done] = '\0';
		return contents;
	}
	len *= 2;
	contents = realloc(contents, len + 1);
	goto more;
}

static inline int fieldname_is(char *test, const char *fieldname)
{
	return (strncmp(test, fieldname, strlen(fieldname)) == 0
		&& test[strlen(fieldname)] == ':');
}

static inline char *field(char *test)
{
	return strchr(test, ':') + 1;
}

static int read_config(int fd)
{
	char *i, *string = suck_file(fd);

	if (!string)
		return 0;

	for (i = strtok(string, "\n"); i; i = strtok(NULL, "\n")) {
		const struct config_entry *e;
		char *val = strchr(i, ':');

		if (!val)
			return 0;
		*val = '\0';
		val++;

		e = in_word_set(i, val - i - 1);
		if (e && !e->parse(val - string, val))
			return 0;
	}
	return 1;
}

/* Find path of compiler, so ccache or distcc don't come back and exec us. */
static char *canonicalize(char *arg0)
{
	char *i, *path, *compiler;

	if (strrchr(arg0, '/'))
		compiler = strrchr(arg0, '/')+1;
	else
		compiler = arg0;

	path = strdup(getenv("PATH") ?: "");

	for (i = strtok(path,":"); i; i = strtok(NULL, ":")) {
		char *fname;

		asprintf(&fname, "%s/%s", i, compiler);
		if (!is_wrapper(fname) && access(fname, X_OK) == 0)
			return fname;
	}
	return NULL;
}

static void run_compile(int fd)
{
	unsigned int i;

	/* Don't search path if they substituted. */
	if (!config.argv_subbed) {
		char *argv0;

		argv0 = canonicalize(config.argv[config.num_prefixes]);
		if (!argv0) {
			if (config.verbose)
				fprintf(stderr,
					"ccontrol: could not find '%s'\n",
					config.argv[config.num_prefixes]);
			too_hard(config.argv);
		}
		config.argv[config.num_prefixes] = argv0;
	}

	if (config.num_compiles_offset) {
		char num_compiles[17];
		config.num_compiles++;

		if (lseek(fd,config.num_compiles_offset,SEEK_SET)==(off_t)-1) {
			if (config.verbose)
				fprintf(stderr, "ccontrol: can't not seek to"
					" %lu in config file\n",
					config.num_compiles_offset);
			too_hard(config.argv);
		}
		sprintf(num_compiles, "%016lx", config.num_compiles);
		if (write(fd, num_compiles, 16) != 16) {
			if (config.verbose)
				fprintf(stderr, "ccontrol: can't write to"
					" %lu in config file\n",
					config.num_compiles_offset);
			too_hard(config.argv);
		}
	}

	if (config.autolimit) {
		double avg;
		if (getloadavg(&avg, 1) == 1
		    && avg > (double)config.autolimit)
			config.num_parallel = 1;
	}

	if (config.num_parallel) {
		struct flock fl;
		unsigned int randnum = getpid();

		fl.l_whence = SEEK_SET;
		fl.l_len = 1;
		fl.l_pid = 0;

		/* Drop lock on entire file first. */
		fl.l_start = 0;
		fl.l_type = F_UNLCK;
		fcntl(fd, F_SETLK, &fl);

		fl.l_type = F_WRLCK;
		for (i = 0; i < config.num_parallel; i++) {
			fl.l_start = ((i + randnum) % config.num_parallel) + 1;
			if (fcntl(fd, F_SETLK, &fl) == 0)
				break;
		}
		/* None free?  Wait on one at random. */
		if (i == config.num_parallel) {
			fl.l_start = (randnum % config.num_parallel)+1;
			if (config.verbose)
				fprintf(stderr, "ccontrol: limiting...\n");
			while (fcntl(fd, F_SETLKW, &fl) < 0 && errno == EINTR);
		}
	} else {
		/* Drop lock early. */
		close(fd);
	}

	if (config.verbose) {
		unsigned int i;
		fprintf(stderr, "Execing: ");
		for (i = 0; i < config.argc; i++)
			fprintf(stderr, "'%s' ", config.argv[i]);
		fprintf(stderr, "\n");
	}

	do_compile(config.argv[0], config.argv);
	if (config.verbose)
		fprintf(stderr, "ccontrol: can't exec '%s'\n", config.argv[0]);
}

int main(int argc, char *argv[])
{
	char *fname;
	int fd;

	asprintf(&fname, "%s/.ccontrol", getenv("HOME"));
	fd = open(fname, O_RDWR);
	if (fd < 0)
		too_hard(argv);

	if (!lock_fd(fd))
		too_hard(argv);

	config.argv = argv;
	config.argc = argc;

	if (!read_config(fd))
		too_hard(argv);

	run_compile(fd);
	too_hard(argv);
}
