/*
 * Copyright (C) 1995 Joao Ventura, Lars Fenneberg
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <linux/ip_acct_user.h>
#include "ipquota.h"
#include "pathnames.h"

void usage(void)
{
	fprintf(stderr,"Usage: %s [-vha] [<username/uid>]\n", pname);
	exit(1);	
}

void main (int argc,char **argv) {

	int uid,flags;
	int count, c;
	signed long quota;
	struct passwd *pwd = NULL;
	FILE *stats;
  	extern int optind; 
  	extern char *optarg;
	int arg_all = 0;

	use_syslog = 0;
	pname = argv[0];

  	while ((c = getopt(argc,argv,"vha")) > 0) 
  	{
  		switch (c)
  		{
			case 'a':
				arg_all++;
				break;
			case 'v':
				version();
				break;
  			case 'h':
  			default:
  				usage();
  				break; /* never reached */
  		}
  	}
	
	if (!(argc-optind)) {
		if (!arg_all) pwd = getpwuid(getuid());
	} else if ((argc-optind)==1) {
		if (arg_all)
		{
			log("option a requires no argument");
			exit(1);
		}
		if (((pwd = getpwnam(argv[1])) == NULL) 
			&& ((pwd = getpwuid(atoi(argv[1]))) == NULL)) 
		{
			log("no such user/uid: %s", argv[1]);
			exit(1);
		}
	} else {
		usage();
	}

	if (getuid() && ((arg_all || getuid()!=pwd->pw_uid))) {
		log("only root can do that");
		exit(1);
	}
	
	if ((stats=fopen(_PATH_VAR_LOG_QUOTA_STATS,"r"))==NULL) {
		log(my_perror(_PATH_VAR_LOG_QUOTA_STATS));
		exit(1);
	} 
	
	if (arg_all)
	{
	  do {
		count = fscanf(stats,"%i %li %i\n", &uid, &quota, &flags);
		if (count != 3) continue;
		if ((pwd = getpwuid(uid)) == NULL)
		{
			printf("%-6i %15li %3i\n",uid,quota, flags);
		}
		else
		{
			printf("%-6s %15li %3i\n",pwd->pw_name,quota, flags);
		}
	  } while (count != EOF);
	} 
	else 
	{
	  do {
		count = fscanf(stats,"%i %li %i\n", &uid, &quota, &flags);
		if (count != 3) continue;
	  } while ((count != EOF) && ((pwd->pw_uid)!=uid));

	  if (count != EOF) {
		printf("%s - ip quota: %li bytes%s.\n",pwd->pw_name,quota,
			(flags&IPAU_NO_ACCESS)?" (access denied)":"");
	  } else {
		printf("%s - no ip quota defined.\n",pwd->pw_name);
	  }
	}

	fclose(stats);
	if (pwd) free(pwd); /* just to be clean */
}
