/database/tags.c
/* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
 * BSD-style license.  Please see the COPYING file for details.
 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/mman.h>
#include "tags.h"
#include "util.h"
#include "database.h"
#include "config.h"
#include "configuration.h"


int tag_scan(const char *author, const char *data, int len, uint64_t record) {
	char *taglist[MAX_TAGS_PER_RECORD];
	char last_char = ' ';
	int n_tags = 0;
	int i, j;

	for (i = 0; i < len; i++) {
tag_scan_start:
		if (WHITESPACE(last_char) && (data[i] == '#' || data[i] == '@')) {
			if (n_tags == MAX_TAGS_PER_RECORD) {
				fprintf(stderr, "Too many tags in message\n");
				break;
			}
			int begin = i;
			int start = ++i;
			while (i < len && VALID_CHAR(data[i]) && (i - start < MAX_TAG_LENGTH)) {
				i++;
			}
			if (start - i == 0) continue;
			char *tag = calloc(1, MAX_TAG_LENGTH + 2);
			memcpy(tag, &data[begin], i - begin);
			for (j = 0; j < n_tags; j++) {
				if (!strncmp(tag, taglist[j], MAX_TAG_LENGTH)) {
					// We already have this tag.  Start over.
					free(tag);
					last_char = data[i-1];
					goto tag_scan_start;
				}
			}
			taglist[n_tags] = tag;
			n_tags++;
			last_char = data[i-1];
			// We goto here so i doesn't get incremented
			goto tag_scan_start;
		}
		last_char = data[i];
	}

	for (i = 0; i < n_tags; i++) {
		tag_add(author, taglist[i], record);
		free(taglist[i]);
	}
	return 1;
}

int tag_add(const char *author, const char *tag, uint64_t record) {
	char filename[FILENAME_MAX];
	struct blergref t;
	const char *tagval = tag + 1;

	memset(t.author, 0, 32);
	strncpy(t.author, author, 32);
	t.record = record;

	switch(tag[0]) {
	case '#':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.hash_tags_path, tagval);
		break;
	case '@':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.ref_tags_path, tagval);
		break;
	default:
		fprintf(stderr, "Invalid tag type: %s\n", tag);
		return 0;
	}

	int tag_fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, 0600);
	flock(tag_fd, LOCK_EX);
	if (tag_fd == -1) {
		perror("Could not open tag file");
		return 0;
	}
	int n = write(tag_fd, &t, sizeof(struct blergref));
	if (n < sizeof(struct blergref)) {
		perror("Could not write new tag");
		return 0;
	}
	flock(tag_fd, LOCK_UN);
	close(tag_fd);

	/* Set a flag for mentioned users */
	if (tag[0] == '@' && blerg_exists(tagval)) {
		struct blerg *b = blerg_open(tagval);
		if (b != NULL) {
			blerg_set_status(b, BLERGSTATUS_MENTIONED, 1);
			blerg_close(b);
		}
	}

	return 1;
}

struct blergref * tag_list(const char *tag, uint64_t offset, int *count, int direction) {
	char filename[FILENAME_MAX];
	struct stat st;
	struct blergref *taglist;
	struct blergref *retlist;
	uint64_t n_tag_records;

	if (!valid_tag_name(tag + 1))
		return NULL;

	if (!(direction == 1 || direction == -1)) {
		fprintf(stderr, "Invalid direction: %d\n", direction);
		return NULL;
	}
	
	switch(tag[0]) {
	case '#':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.hash_tags_path, tag + 1);
		break;
	case '@':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.ref_tags_path, tag + 1);
		break;
	default:
		fprintf(stderr, "Invalid tag type: %s\n", tag);
		return NULL;
	}

	int tag_fd = open(filename, O_RDONLY, 0600);
	if (tag_fd == -1) {
		perror("Could not open tag file");
		goto tag_list_open_failed;
	}

	fstat(tag_fd, &st);
	if (st.st_size == 0) {
		goto tag_list_map_failed;
	}
	n_tag_records = st.st_size / sizeof(struct blergref);
	if (*count > n_tag_records - offset)
		*count = n_tag_records - offset;
	if (offset > n_tag_records) {
		fprintf(stderr, "Cannot access tag record beyond end\n");
		goto tag_list_map_failed;
	}

	taglist = (struct blergref *) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, tag_fd, 0);
	if (taglist == MAP_FAILED) {
		perror("Could not mmap tag file");
		goto tag_list_map_failed;
	}
	retlist = (struct blergref *) malloc(sizeof(struct blergref) * *count);
	if (retlist == NULL) {
		perror("Could not allocate memory for tag list");
		goto tag_list_malloc_failed;
	}
	switch(direction) {
	case 1:
		memcpy(retlist, taglist + offset, sizeof(struct blergref) * *count);
		break;
	case -1:
		memcpy(retlist, taglist + (n_tag_records - *count - offset), sizeof(struct blergref) * *count);
		break;
	}

	munmap(taglist, st.st_size);
	close(tag_fd);
	return retlist;

tag_list_malloc_failed:
	munmap(taglist, st.st_size);
tag_list_map_failed:
	close(tag_fd);
tag_list_open_failed:
	*count = 0;
	return NULL;
}

int tag_exists(const char *tag) {
	char filename[FILENAME_MAX];

	if (!valid_tag_name(tag + 1))
		return 0;

	if (!(tag[0] == '@' || tag[0] == '#')) {
		fprintf(stderr, "Invalid tag: %s\n", tag);
		return 0;
	}

	switch(tag[0]) {
	case '#':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.hash_tags_path, tag + 1);
		break;
	case '@':
		snprintf(filename, FILENAME_MAX, "%s/%s", blergconf.ref_tags_path, tag + 1);
		break;
	default:
		fprintf(stderr, "Invalid tag type: %s\n", tag);
		return 0;
	}
	if (access(filename, F_OK) == -1)
		return 0;
	else
		return 1;
}