/*
#ident "@(#)smail/pd/sdbm:RELEASE-3_2_0_120:dba.c,v 1.2 2003/03/27 16:49:22 woods Exp"
 */
/*
 * dba	dbm analysis/recovery
 */

#include "defs.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#include "tune.h"
#include "sdbm.h"

#if defined(UNIX_SYS5) || defined(POSIX_OS) || defined(USE_FCNTL)
# include <fcntl.h>
#else
# if defined(UNIX_BSD)
#  include <sys/file.h>
# endif
#endif

char *progname;
extern int main __P((int, char **));
extern void oops __P((char *, ...));		/* util.c */
extern int okpage __P((char *));		/* util.c */

static void sdump __P((int));
static int pagestat __P((char *));


int
main(argc, argv)
	int argc;
	char **argv;
{
	size_t n;
	char *p;
	char *name;
	int pagf;

	progname = argv[0];

	if ((p = argv[1])) {
		name = (char *) malloc((n = strlen(p)) + 5);
		strcpy(name, p);
		strcpy(name + n, ".pag");

		if ((pagf = open(name, O_RDONLY)) < 0)
			oops("cannot open %s.", name);

		sdump(pagf);
	}
	else
		oops("usage: %s dbname", progname);

	exit(0);
	/* NOTREACHED */
}

static void
sdump(pagf)
	int pagf;
{
	register int b;
	register int n = 0;
	register int t = 0;
	register int o = 0;
	register int e;
	char pag[PBLKSIZ];

	while ((b = read(pagf, pag, PBLKSIZ)) > 0) {
		printf("#%d: ", n);
		if (!okpage(pag))
			printf("bad\n");
		else {
			printf("ok. ");
			if (!(e = pagestat(pag)))
			    o++;
			else
			    t += e;
		}
		n++;
	}

	if (b == 0)
		printf("%d pages (%d holes):  %d entries\n", n, o, t);
	else
		oops("read failed: block %d", n);
}

static int
pagestat(pag)
	char *pag;
{
	register int n;
	register int free;
	register short *ino = (short *) pag;

	if (!(n = ino[0]))
		printf("no entries.\n");
	else {
		free = ino[n] - (n + 1) * sizeof(short);
		printf("%3d entries %2d%% used free %d.\n",
		       n / 2, ((PBLKSIZ - free) * 100) / PBLKSIZ, free);
	}
	return n / 2;
}
