#include "conf-update.h"

bool user_modified(char *file) {
	FILE *indexpipe, *filepipe;
	char *line = NULL;
	char *filedump = NULL;
	size_t len = 0, len2 = 0;
	char *md5sum;
	unsigned char filemd5[MD5_DIGEST_LENGTH];
	char hexdigest[32];
	bool user_mod = TRUE;
	if (access(MD5SUM_INDEX, R_OK) != 0) {
		return TRUE;
	} else {
		indexpipe = fopen(MD5SUM_INDEX, "r");
		exit_error(indexpipe, MD5SUM_INDEX);
		while (getline(&line, &len, indexpipe) != -1) {
			if (!strncmp(line, file, strlen(file)) && *(line + strlen(file)) == ' ') {
				md5sum = strrchr(line, ' ') + 1;
				filepipe = fopen(file, "r");
				exit_error(filepipe, file);
				if (getdelim(&filedump, &len2, EOF, filepipe) != -1) {
					MD5((unsigned char *)filedump, strlen(filedump), filemd5);
					md52hex(filemd5, hexdigest);
					if (!strncmp(md5sum, hexdigest, 32)) {
						user_mod = FALSE;
					}
				}
				fclose(filepipe);
				free(filedump);
			}
		}
		fclose(indexpipe);
		free(line);
		return user_mod;
	}
}

void md52hex(unsigned char *md5sum, char *hexdigest) {
	// this one is stolen from python's md5module.c
	char c;
	int i, j = 0;
	
	for(i=0; i<16; i++) {
		c = (md5sum[i] >> 4) & 0xf;
   		hexdigest[j] = (c>9) ? c+'a'-10 : c + '0';
   		j++;
		c = (md5sum[i] & 0xf);
		hexdigest[j] = (c>9) ? c+'a'-10 : c + '0';
		j++;
    } 
}

void calc_md5(char *file, char* hexdigest) {
	FILE *fp;
	char *dump = NULL;
	size_t len = 0;
	
	unsigned char md5sum[MD5_DIGEST_LENGTH];
	
	fp = fopen(file, "r");
	if (getdelim(&dump, &len, EOF, fp) != -1) {
		MD5((unsigned char *)dump, strlen(dump), md5sum);
		md52hex(md5sum, hexdigest);
		free(dump);
	}
	fclose(fp);
}

void md5sum_update(char *file, char *hexdigest) {
	FILE *oldpipe;
	char *dump = NULL;
	size_t len = 0;
	char *entry;

	oldpipe = fopen(MD5SUM_INDEX, "r");
	exit_error(oldpipe, MD5SUM_INDEX);
	
	if ((getdelim(&dump, &len, EOF, oldpipe) != -1) && (entry = strstr(dump, file))) {
		entry = strchr(entry, '\n') - 32;
		strncpy(entry, hexdigest, 32);
		exit_error(freopen(MD5SUM_INDEX, "w", oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(dump, strlen(dump), sizeof(char), oldpipe), MD5SUM_INDEX);
	} else {
		// there's no entry at all yet
		exit_error(freopen(MD5SUM_INDEX, "a", oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(file, strlen(file), sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(" ", strlen(" "), sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(hexdigest, 32, sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite("\n", strlen("\n"), sizeof(char), oldpipe), MD5SUM_INDEX);
	}
	free(dump);
	fclose(oldpipe);
}
