/* write.c - write an entry to an LDB file
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "lock.h"
#include "ldb.h"


/* Write an LDB entry for LDB structure "d", overwriting any previously
 * stored entry for that file. The LDB used is "ldbfile".
 *
 * While writing takes place, "ldbfile" is locked, and the locking blocks
 * - i.e. the process will wait until whoever else has locked the file
 * unlocks it.
 *
 * If "ldbfile" does not exist, it is created with mode 660.
 */
void ldb_write(char *ldbfile, ldb_t d)
{
	FILE *fptr;
	int fd;
	long i;

	if ((!ldbfile) || (!d))
		return;

	fd = open(ldbfile, O_RDONLY);
	if (fd < 0) {			    /* create new file */
		fd = open(ldbfile, O_WRONLY | O_CREAT | O_EXCL,
			  S_IRUSR | S_IWUSR);
		if (fd < 0)
			return;
		fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	}
	close(fd);

	fd = open(ldbfile, O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
	if (fd < 0)
		return;			    /* failed to open LDB file */

	my_flock(ldbfile, fd, LOCK_EX);	    /* lock file */

	i = ldb_find(ldbfile, d->filename);

	if (i >= 0) {			    /* entry already exists */
		ldb_cache_flags[i] = LDB_FLAG_ALTERED;
		sprintf(ldb_cache_data[i],
			"%08lX-%08lX-%08lX-%08lX-%1d/%1d",
			d->last_accessed, d->last_datestamp,
			d->datestamp_line, d->current_line, d->at_end,
			d->sub_status);
		ldb_save(ldbfile);
	} else {			    /* append new entry */
		fptr = fopen(ldbfile, "a");
		if (fptr) {
			fseek(fptr, 0, SEEK_END);
			fprintf(fptr,
				"%s%c %08lX-%08lX-%08lX-%08lX-%1d/%1d\n",
				d->filename, 1, d->last_accessed,
				d->last_datestamp, d->datestamp_line,
				d->current_line, d->at_end, d->sub_status);
			fclose(fptr);
		}
		ldb_load(ldbfile);
	}

	my_flock(ldbfile, fd, LOCK_UN);	    /* unlock file */
	close(fd);
}

/* EOF */
