/* purge.c - purge obsolete entries from LDB file
 */

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


/* Purge file "ldbfile" of entries relating to nonexistent files, reporting
 * errors as being from program "pn".
 *
 * Returns nonzero on error.
 */
int ldb_purge(char *ldbfile, char *pn)
{
	int removed = 0;
	struct stat sb;
	long i;
	int fd;

	if (!ldbfile) {
		fprintf(stderr, "%s: cannot purge - no LDB specified\n\r",
			pn);
		return (1);
	}

	ldb_init();

	fd = open(ldbfile, O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "%s: failed to read LDB file '%s'\n\r", pn,
			ldbfile);
		return (1);
	}

	printf("--- Purging LDB file '%s'\n", ldbfile);

	my_flock(ldbfile, fd, LOCK_EX);

	ldb_load(ldbfile);

	for (i = 0; i < ldb_cached_entries; i++) {

		if (stat(ldb_cache_names[i], &sb)) {
			if (removed == 0)
				printf("\n");
			printf(" %s (%s)\n", ldb_cache_names[i],
			       strerror(errno));
			ldb_cache_flags[i] |= LDB_FLAG_DELETED;
			removed++;
			continue;
		}

		if ((!S_ISREG(sb.st_mode)) && (!S_ISDIR(sb.st_mode))) {
			if (removed == 0)
				printf("\n");
			printf(" %s (not a regular file)\n",
			       ldb_cache_names[i]);
			ldb_cache_flags[i] |= LDB_FLAG_DELETED;
			removed++;
			continue;
		}
	}

	if (removed > 0)
		printf("\n");

	printf("--- Entries removed: %d\n", removed);

	ldb_save(ldbfile);

	my_flock(ldbfile, fd, LOCK_UN);
	close(fd);

	return (0);
}

/* EOF */
