/*
 * Copyright (c) 2003-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

#include	<stdio.h>
#include	<sys/types.h>
#include	<sys/file.h>
#ifndef DB4
#include	<ndbm.h>
#else
#define         DB_DBM_HSEARCH  1
#include	<db.h>
#endif
#include	<syslog.h>
#include	<unistd.h>
#include	<stdlib.h>

#include	"firewall.h"
#include	"auth.h"
#include	"authdb.h"
#include        "gp_list.h"

static	char*	moduleId ATTR_UNUSED = "$Id: authdump.c,v 1.7 2007/09/10 02:49:12 arkenoi Exp $";

static	Cfg	*confp;
static	int	tin;

static int dumpauthgroups(Group gp[]);
static void dumpauth(char*,Auth*);

int
main(ac,av)
int	ac;
char	*av[];
{
	Auth	ab;
	char	u[512];
	int	recs = 0;

	tin  = (isatty(2) && !isatty(1));

	if((confp = cfg_read("authsrv")) == (Cfg *)-1) {
		fprintf(stderr,"Warning: cannot read configuration file\n");
		confp = (Cfg *)0;
	}

	if(auth_dbconfig(confp) || auth_dbopen()) {
		fprintf(stderr,"Cannot open auth database!\n");
		exit(1);
	}
	if(auth_dbtraversestart(u,&ab) == 0) {
		dumpauth(u,&ab);
		recs++;
		if(tin)
			fprintf(stderr,".");
		while(auth_dbtraversenext(u,&ab) == 0) {
			dumpauth(u,&ab);
			if(tin)
				fprintf(stderr,".");
			recs++;
		}
	}
	auth_dbclose();
	if(tin)
		fprintf(stderr,"\n%d records dumped\n",recs);
	exit(0);
}

static void
dumpauth(user,a)
char	*user;
Auth	*a;
{
	printf("\nuser=%s\n",user);
	printf("longname=%s\n",a->ln);
	dumpauthgroups(a->gp);
	printf("pass=%s\n",a->pw);
	printf("flags=%o\n",a->flgs);
	printf("bad_count=%d\n",a->bcnt);
	printf("proto=%c\n",a->atyp);
	printf("last=%ld\n",a->last);
	printf("lastpw=%ld\n",a->lastpw);
}


static int 
dumpauthgroups(Group gp[])
{
	int i;

	printf("group=");

	for(i=0; i < AUTH_GNUM; i++)
	{
	  if(end_gp_list(gp,i))       
	    break;

 	  printf("%s:%o ",gp[i].name, gp[i].flgs);

	}

	printf("\n");
	return 0;
}	
