#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "sbs.h"
#include "db.h"

/**************************************************
 * sbs_add adds each of the arguments in argv to the appropriate
 * database file
 **************************************************/

void
sbs_add(int argc, char *argv[]) 
{
    int i;
    char *dirname;
    char *fname;
    char cwd[PATH_MAX];
    FILE *fp;

    if(argc == 2) {
	fprintf(stderr, "Specify one or more files to add\n");
	exit(1);
    }
    
    if( (getcwd(cwd, PATH_MAX)) == NULL) {
	perror("getcwd");
	exit(1);
    }
    
    for(i = 2; i < argc; i++) {
	dirname = split_path(argv[i], &fname);
	if(dirname != NULL) {
	    if((chdir(dirname)) == -1) {
		perror("chdir");
		exit(1);
	    }
	}

	if((fp = fopen(fname, "r")) == NULL) {
	    fprintf(stderr, "File %s does not exist\n", argv[i]);

	} else 	if((db_find(fname)) != -1) {
	    fprintf(stderr, "%s has already been added\n", argv[i]);

	} else {
	    db_add(fname);
	}

	/* Go back to the directory we started in */
	if((chdir(cwd)) == -1) {
	    perror("chdir");
	    exit(1);
	}
    }

}
