#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 "db.h"
#include "sbs.h"

void do_update(char *name);
void
sbs_update(int argc, char *argv[])
{
    char path[PATH_MAX];
    int i;

    if(argc == 2) {
	/* update the current working directory */
	getcwd(path, PATH_MAX);
	do_update(path);

    } else {
	/* commit each file or directory */
	for(i = 2; i < argc; i++) {
	    do_update(argv[i]);
	}
    }

}

void
do_update(char *name)
{
    char temppath[PATH_MAX], cwd[PATH_MAX];
    char *path, *ptr, *fname;
    char repo_path[PATH_MAX];
    struct stat st;

    if( (getcwd(cwd, PATH_MAX)) == NULL) {
	perror("getcwd");
	exit(1);
    }

    /* construct the path */
    path = get_abs_path(name);

    /* parse the path to determine where the repository tree begins */

    /* check if path is a file or a directory */
    strncpy(temppath, path, sizeof(temppath));
    if( (stat(temppath, &st)) == -1) {
	perror("stat");
	exit(1);
    }
    if(!S_ISDIR(st.st_mode)) {

	/* strip off the file name from the path string */
	if((ptr = split_path(temppath, &fname)) == NULL) {
	    fprintf(stderr, "Error from splitpath\n"); /* shouldn't happen */
	}
	
	get_repository_path(repo_path, temppath, PATH_MAX);

	printf("Path in repository is %s\n", repo_path);

	/* add file name back to the repo_path */

	strncat(repo_path, "/", 2);
	strncat(repo_path, fname, strlen(fname) +1);  
	
	if((set_most_recent(repo_path)) == -1) {
	    fprintf(stderr, "Could not find file in repository\n");
	    return;
	}
	/* copy the file */
	copy_file(repo_path, path);
	
    } else {
	get_repository_path(repo_path, path, PATH_MAX);
	printf("Path in repository is %s\n", repo_path);

	/* copy the dir */
	update_dir(path, repo_path);
    }  
} 
