/* db.c - contains functions to manipulate a database of file names
 * Each of the functions assume the database is given by DBFILE and is in the
 * current working directory.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include "db.h"

/************************************************
 * db_find returns the offset into DBFILE where name occurs, 
 * or -1 if name is not in the database.
 ************************************************/

long
db_find(char *name) 
{
    char *np;
    FILE *fp = fopen(DBFILE, "r");
    long position;
    
    char record[PATH_MAX]; 
    
    if(fp == NULL) {
	return -1;
    } else {
	position = ftell(fp); /* Record the file offset before we read */

	while( (fgets(record, 100*sizeof(char), fp)) != NULL ) {

	    /* remove the newline */
	    if( (np = index(record, '\n')) != NULL ) {
		*np = '\0';
	    }

	    /* if we find the file name, return */
	    if((strcmp(name, record)) == 0 ) {
		fclose(fp);
		return position;
	    }
	    position = ftell(fp);

	}
	fclose(fp);
	return -1;
    }
}

/************************************************
 * db_add adds name to the end of DBFILE
 ************************************************/

void
db_add(char *name) 
{
    FILE *fp = fopen(DBFILE, "a");
    if(fp == NULL) {
	fprintf(stderr, "Could not open %s\n", DBFILE);
	exit(1);
    }
    fprintf(fp, "%s\n", name);
    fclose(fp);
}


/************************************************
 * db_exists returns 1 if DBFILE exists in dirname and 0 otherwise
 ************************************************/

int
db_exists(char *dirname) 
{
    struct dirent *entry;
    DIR *dir = opendir(dirname);
    if(dir == NULL) {
	perror("opendir");
	exit(1);
    }

    while( (entry = readdir(dir)) != NULL ) {
	if( (strcmp(entry->d_name, DBFILE)) == 0 ) {
	    /* match found */
	    closedir(dir);
	    return 1;
	}
    }
    /* no match found */
    closedir(dir);
    return 0;
}
