/* $Id$ */

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#define PATH_DIR	"/home/gophi/.loggit/"
#define PATH_CACHE	PATH_DIR "cache"
#define PATH_CACHE_TMP	PATH_DIR "cache~"

#define PATH_FILE	"/home/gophi/irclogs/freenode/#pregierz.log"

static void cleanup(void)
{
	fprintf(stderr, "Cleaning up\n");
	unlink(PATH_CACHE_TMP);
}

static off_t load_cache(void)
{
	FILE *fp;
	off_t off;

	fp = fopen(PATH_CACHE, "r");
	if (!fp)
		return 0;

	if (fscanf(fp, "%u", &off) != 1) {
		fclose(fp);
		return 0;
	}

	fclose(fp);
	return off;
}

static int save_cache(off_t off)
{
	FILE *fp;

	fp = fopen(PATH_CACHE_TMP, "w");
	if (!fp)
		return -1;

	if (fprintf(fp, "%u", off) < 0) {
		fclose(fp);
		return -1;
	}

	fclose(fp);
	unlink(PATH_CACHE);
	rename(PATH_CACHE_TMP, PATH_CACHE);
	return 0;
}

static int update_offset(off_t *off)
{
	struct stat st;
	FILE *fp;

	if (stat(PATH_FILE, &st) == -1)
		return -1;

	fp = fopen(PATH_FILE, "r");
	if (!fp)
		return -1;

	if (fseek(fp, *off, SEEK_SET) == -1) {
		fclose(fp);
		return -1;
	}

	for (;;) {
		int ch = fgetc(fp);
		if (ch == EOF)
			break;

		fputc(ch, stdout);
	}

	fclose(fp);
	*off = st.st_size;
	return -0;
}

int main(void)
{
	off_t off;

	atexit(cleanup);

	off = load_cache();
	if (off == 0)
		fprintf(stderr, "Warning: Cannot load cache, assuming 0\n");

	if (update_offset(&off) == -1) {
		fprintf(stderr, "Cannot update cache\n");
		exit(EXIT_FAILURE);
	}

	if (save_cache(off) == -1) {
		fprintf(stderr, "Cannot save cache\n");
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);

	/* NOTREACHED */
	return 0;
}
