/* read.c - read an entry from an LDB file
 */

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


/* Read an LDB entry for "file" into LDB structure "d", or just blank "d" if
 * no entry could be found. The LDB used is "ldbfile".
 *
 * While reading takes place, "ldbfile" is locked, and the locking blocks
 * - i.e. the process will wait until whoever else has locked the file
 * unlocks it.
 */
void ldb_read(char *ldbfile, char *file, ldb_t d)
{
	int fd;
	int i;

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

	file = ldb_filename(file);

	strcpy(d->filename, file);
	d->last_accessed = 0;
	d->last_datestamp = 0;
	d->datestamp_line = 0;
	d->current_line = 0;
	d->at_end = 0;
	d->sub_status = 0;

	if (!ldbfile)
		return;

	fd = open(ldbfile, O_RDWR);
	if (fd < 0)
		return;			    /* failed to read LDB file */

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

	i = ldb_find(ldbfile, file);	    /* find LDB entry */

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

	if (i < 0)
		return;			    /* not found in LDB */

	sscanf(ldb_cache_data[i], "%8lx-%8lx-%8lx-%8lx-%1d/%1d",
	       &(d->last_accessed), &(d->last_datestamp),
	       &(d->datestamp_line), &(d->current_line),
	       &(d->at_end), &(d->sub_status)
	    );

	return;
}

/* EOF */
