#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>

#define COLOR(c,b) "\e[" c ";" b "m"

typedef struct {
	const char *name;
	char value[32];
} pairtype;


static pairtype color_pairs[] = {
	{"blue", COLOR("34", "01") },
	{"brown", COLOR("00", "33") },
	{"darkblue", COLOR("00", "34") },
	{"darkgreen", COLOR("00", "32") },
	{"darkred", COLOR("00", "31") },
	{"faint", COLOR("00", "2") },
	{"fuchsia", COLOR("35", "01") },
	{"green", COLOR("32", "01") },
	{"purple", COLOR("00", "35") },
	{"red", COLOR("31", "01") },
	{"teal", COLOR("00", "36") },
	{"turquoise", COLOR("36", "01") },
	{"yellow", COLOR("1", "33") },
};
#define ARR_SIZE(arr) (sizeof(arr) / sizeof(*arr))

static char *COLOR_MAP = "/etc/portage/color.map";

int main(int argc, char **argv) {
	FILE *fp;
	char color = 1;
	int i, x;

	if (getenv("NOCOLOR")) {
		color = 0;
	}

	if ((color) && (access(COLOR_MAP, R_OK) == 0)) {
		char buf[512];
		char *p;
		if ((fp = fopen(COLOR_MAP, "r")) == NULL)
			return 1;
		while(fgets(buf, sizeof(buf), fp) != NULL) {
			if (strchr(buf, '=') == NULL)
				continue;
			if (buf[0] == '#')
				continue;
			if ((p = strchr(buf, '\r')) != NULL)
				*p = 0;
			if ((p = strchr(buf, '\n')) != NULL)
				*p = 0;

			p = strchr(buf, '=');
			*p = 0;
			for (i = 0 ; i < ARR_SIZE(color_pairs); i++) {
				if (strcmp(buf, color_pairs[i].name) == 0) {
					snprintf(color_pairs[i].value, sizeof(color_pairs[i].value), "\e[%s", p + 1);
				}
			}
		}
		fclose(fp);
	}
	if (!color)
		for (i = 0 ; i < ARR_SIZE(color_pairs); i++)
			color_pairs[i].value[0] = 0;

	if (argc > 1) {
		for (i = 0 ; i < ARR_SIZE(color_pairs); i++) {
			for (x = 1 ; x < argc ;x++)
				if (strcmp(color_pairs[i].name, argv[x]) == 0)
					printf("%s=%s\n", color_pairs[i].name, color_pairs[i].value);
		}
	} else {
		for (i = 0 ; i < ARR_SIZE(color_pairs); i++)
			printf("%s=%s\n", color_pairs[i].name, color_pairs[i].value);
	}
	return 0;
}
