/*
 * Copyright (c) 1998 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the Kungliga Tekniska
 *      Högskolan and its contributors.
 * 
 * 4. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_MODE_H
#include <sys/mode.h>
#endif
#include <sys/param.h>
#include <dirent.h>
#include <roken.h>
#include <err.h>
#include <signal.h>
#if defined(HAVE_DBM_H)
#include <dbm.h>
#elif defined(HAVE_NDBM_H)
#include <ndbm.h>
#else
#error No supported DB format
#endif
#include "romedia.h"
#include "fs.h"
#include "mbuf.h"
#include "mdir.h"

DBM *db;

void
open_db(char *db_name)
{ 
    db = dbm_open(db_name, O_CREAT|O_RDWR|O_EXCL, 0600);
   
    if(!db)
	errx(1, "failed to create db\n");
}

int
enter_db(char *index, char *data)
{
    datum   key, contents;
    
    key.dsize = strlen(index);
    key.dptr = index ;

    contents.dsize = strlen(data) ;
    contents.dptr = data;

    dbm_store(db, key, contents, DBM_REPLACE);
    return 0;
}

void
close_db(void)
{
    if (db)
	dbm_close(db);
}


int index_entry(char *path, ino_t parent)
{
    AFSFid dot = { 1 ,1 ,1 }, dot_dot = { 1, 1, 1 }; /* This doesn't matter */
    struct stat sb;
    char str[MAXPATHLEN+STATUS+NUMSIZE*2];
    char num[NUMSIZE];
    struct dirent *dp;
    char type;

    if (lstat(path, &sb) == -1)
	errx(1, "Error stat()ing %s", path);

    if (S_ISDIR(sb.st_mode))
	type = 'd';
    else if (S_ISREG(sb.st_mode))
	type = 'f';
    else if (S_ISLNK(sb.st_mode))
	type = 'l';
    else  /* Type is unknown ignore */
	return 0;

    if (S_ISDIR(sb.st_mode)) {
	DIR *dir;
	mbuf somebuf;

	if (mbuf_create(&somebuf, -1, 0, 0, MBUF_ANON))
	    errx(1, "failed mbuf_create");
	
	if (mdir_mkdir(&somebuf, dot, dot_dot))
	    errx(1, "failed mdir_mkdir");

	dir = opendir(path);
	if (!dir)
	    errx(1, "failed opening %s", path);

	while ((dp = readdir(dir)) != NULL) {    
	    char newpath[MAXPATHLEN];

	    if (mdir_creat(&somebuf, dp->d_name, dot))
		errx(1, "mkdir_creat");

	    if (strcmp(dp->d_name, ".") == 0 || 
		strcmp(dp->d_name, "..") == 0)
		continue;

	    snprintf(newpath, MAXPATHLEN, "%s/%s", path, dp->d_name);
	    index_entry(newpath, parent == 0 ? 1 : sb.st_ino);
	}
	sb.st_size = somebuf.len;
	mbuf_end(&somebuf);
	closedir(dir);
    }

    snprintf(str, sizeof(str), "%c:%d:%d:%d:%s",
	     type, 
	     (int) sb.st_size,
	     parent==0 ? 1 : parent,
	     (int) sb.st_mtime,
	     path);
    snprintf(num, NUMSIZE, "%d", parent == 0 ? 1 : sb.st_ino);

    printf("Inserting: %s <-- %s\n", num, str);
    enter_db(num, str);


    return 0;
}

int main(int argc, char **argv)
{
    char *path;
    char *db_name;
    int i ;

    set_progname(argv[0]);

    if (argc != 3)
	errx(1, "%s db abspath", argv[0]);

    db_name = strdup(argv[1]);
    path = strdup(argv[2]);

    if (!path || !db_name)
	errx(1, "strdup failed\n");

    open_db(db_name);

    if (*path != '/')
	errx(1, "path (%s) need to absolute", path);
    
    i = strlen(path)-1;
    if (path[i] == '/')
	path[i] = '\0';

    index_entry(path, 0);

    close_db();

    return 0;
}

