/* Parsing for "option" in .ccontrol file.  It can be fairly complex.
   Compiler option parsing stolen from ccache:
   Copyright (C) Andrew Tridgell 2002
 */
#define _GNU_SOURCE
#include <fnmatch.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "ccontrol.h"

#include "option_hash.c"

static char *canonicalize(const char *filename)
{
	char *fname;
	unsigned int i, oldlen, len, prevslash, prev_used;

	if (filename[0] == '/')
		fname = strdup(filename);
	else
		asprintf(&fname, "%s/%s", get_current_dir_name(), filename);

	len = strlen(fname);
again:
	prevslash = 0;
	prev_used = 0;
	oldlen = len;

	for (i = 0; i < len; i++) {
		unsigned int strip = 0;

		if (fname[i] != '/')
			continue;

		if (fname[i+1] == '.') {
			/* Strip /./ */
			if (fname[i+2] == '/')
				strip = 2;
			/* Strip /../ (only works once for each ../) */
			else if (fname[i+2] == '.'
				 && fname[i+3] == '/'
				 && !prev_used) {
				strip = (i + 3) - prevslash;
				i = prevslash;
				prev_used = 1;
			}
		} else
			/* Strip multiple // */
			while (fname[i+strip+1] == '/')
				strip++;

		memmove(fname + i, fname + i + strip, len + 1 - i);
		len -= strip;
		prevslash = i;
	}
	if (len != oldlen)
		goto again;

	return fname;
}

#if 0
int main(int argc, char *argv[])
{
	printf("%s\n", canonicalize(argv[1] ?: ""));
	return 0;
}
#endif

static char *find_filename(void)
{
	unsigned int i;
	char *filename = NULL;
	struct stat st;

	for (i = 1; i < config.argc; i++) {
		/* These take a filename option.  Skip it. */
		if (is_multiword_option(config.argv[i],
					strlen(config.argv[i]))) {
			i++;
			continue;
		}

		if (config.argv[i][0] == '-')
			continue;

		/* if an argument isn't a plain file then assume its
		   an option, not an input file. This allows us to
		   cope better with unusual compiler options */
		if (stat(config.argv[i], &st) != 0 || !S_ISREG(st.st_mode)) 
			continue;			

		/* More than one filename? eg. called for link. */
		if (filename) {
			filename = NULL;
			break;
		}
		filename = config.argv[i];
	}
	
	return canonicalize(filename ?: "");
}

static int matches_env(char *env_match)
{
	char *env;

	if (!strchr(env_match, '='))
		asprintf(&env_match, "%s=*", env_match);

	for (env = environ[0]; *env; env++) {
		if (fnmatch(env_match, env, 0) == 0)
			return 1;
	}
	return 0;
}

static void strip_opts(char *opts)
{
	char *o;
	unsigned int i;

	for (o = strtok(opts, " "); o; o = strtok(NULL, " ")) {
		for (i = 0; i < config.argc; i++) {
			if (streq(config.argv[i], o)) {
				memmove(config.argv+i, config.argv+i+1,
					sizeof(config.argv[0])
					       * (config.argc-i));
				config.argc--;
			}
		}
	}
}

static void add_opts(char *opts)
{
	char *o;

	for (o = strtok(opts, " "); o; o = strtok(NULL, " ")) {
		config.argv = realloc(config.argv,
				      (config.argc+1)*sizeof(config.argv[0]));

		memmove(config.argv + config.num_prefixes + 1, 
			config.argv + config.num_prefixes,
			sizeof(config.argv[0]) 
			* (config.argc - config.num_prefixes));
		config.argv[config.num_prefixes] = o;
		config.argc++;
	}
}

static void add_env(char *envs)
{
	char *e;

	for (e = strtok(envs, " "); e; e = strtok(NULL, " ")) {
		char *eq = strchr(e, '=');

		if (eq) {
			*eq = '\0';
			eq++;
		} else
			eq = "";
			
		setenv(e, eq, 1);
	}
}

static char *next_opt(char **start)
{
	int len;
	char *oldstart = *start;

	len = strcspn(oldstart, ";");
	if (oldstart[len])
		oldstart[len++] = '\0';
	*start += len;
	return oldstart;
}

int parse_option(unsigned int pos, const char *value)
{
	char *str = strdup(value);
	char *comp_match, *file_match, *env_match, *comp_sub,
		*opts_add, *opts_remove, *env_add;

	/* Do we match? */
	comp_match = next_opt(&str);
	if (!streq(comp_match, "")
	    && fnmatch(comp_match, config.argv[config.num_prefixes], 0) != 0)
		return 1;

	file_match = next_opt(&str);
	if (!file_match)
		return 0;
	if (!streq(file_match, "")
	    && fnmatch(file_match, find_filename(), 0) != 0)
		return 1;

	env_match = next_opt(&str);
	if (!env_match)
		return 0;
	if (!streq(env_match, "")) {
		int need_match = 1;
		if (env_match[0] == '!') {
			need_match = 0;
			env_match++;
		}
		if (matches_env(env_match) != need_match)
			return 1;
	}

	/* OK, perform substitutions requested. */
	comp_sub = next_opt(&str);
	opts_remove = next_opt(&str);
	opts_add = next_opt(&str);
	env_add = next_opt(&str);

	if (!comp_sub || !opts_remove || !opts_add || !env_add)
		return 0;

	if (!streq(comp_sub, "")) {
		config.argv[config.num_prefixes] = comp_sub;
		config.argv_subbed = 1;
	}
	if (!streq(opts_remove, ""))
		strip_opts(opts_remove);
	if (!streq(opts_add, ""))
		add_opts(opts_add);
	if (!streq(env_add, ""))
		add_env(env_add);
	return 1;
}
