#include <stdio.h>
#include <unistd.h>
#include <libmegapixels.h>
#include "config.h"

#ifndef SYSCONFDIR
#define SYSCONFDIR "/etc"
#endif
#ifndef DATADIR
#define DATADIR "/usr/share"
#endif

static int
find_device_by_model(ssize_t maxlen, char *conffile, char *model, int print)
{
	// Check config/%model.conf in the current working directory

	snprintf(conffile, maxlen, "config/%s.conf", model);
	if (print) {
		printf("- %s\n", conffile);
	}
	if (access(conffile, F_OK) != -1) {
		return 1;
	}

	// Check user overridden /etc/megapixels/config/%model.conf
	snprintf(conffile, maxlen, "%s/megapixels/config/%s.conf", SYSCONFDIR, model);
	if (print) {
		printf("- %s\n", conffile);
	}
	if (access(conffile, F_OK) != -1) {
		return 1;
	}

	// Check packaged /usr/share/megapixels/config/%model.conf
	snprintf(conffile, maxlen, "%s/megapixels/config/%s.conf", DATADIR, model);
	if (print) {
		printf("- %s\n", conffile);
	}
	if (access(conffile, F_OK) != -1) {
		return 1;
	}
	if (print) {
		printf("no config for '%s'\n", model);
	}
	return 0;
}

int
libmegapixels_find_config_verbose(ssize_t maxlen, char *configfile, int print)
{
	char model[512];
	FILE *fp;

	if (access("/proc/device-tree/compatible", F_OK) == -1) {
		return 0;
	}
	fp = fopen("/proc/device-tree/compatible", "r");
	char *modelptr = model;
	while (1) {
		int c = fgetc(fp);
		if (c == EOF) {
			return 0;
		}
		*(modelptr++) = (char) c;
		if (c == 0) {
			if (find_device_by_model(maxlen, configfile, model, print)) {
				return 1;
			}
			modelptr = model;
		}
	}
}

int
libmegapixels_find_config(ssize_t maxlen, char *configfile)
{
	return libmegapixels_find_config_verbose(maxlen, configfile, 0);
}