/*
 * 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 <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/ip_acct_user.h>
#include "ipquota.h"
#include "pathnames.h"

int skfd = -1;

void usage(void)
{
	fprintf(stderr,"Usage: %s [-vh]\n", pname);
	fprintf(stderr,"(To be called from ipacctd)\n");
	exit(1);
}

void catch_sig(int sig)
{
	close_database(_PATH_VAR_LOG_QUOTA_STATS);
	log("terminating (signal %i)", sig);
	exit(0);
}

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

	uid_t uid;
	unsigned int sent, recv;
  	extern int optind; 
  	extern char *optarg;
  	int c;
	
	use_syslog = 1;	
	pname = argv[0];
	openlog(argv[0], LOG_PID, LOG_DAEMON);

  	while ((c = getopt(argc,argv,"vh")) > 0) 
  	{
  		switch (c)
  		{
			case 'v':
					version();
					break;
  			case 'h':
  			default:
  					usage();
  					break; /* never reached */
  		}
  	}

	signal(SIGINT, catch_sig);
	signal(SIGTERM, SIG_IGN); /* ignore this so that we can
				     finish our last accouting run */
	signal(SIGQUIT, catch_sig);
	signal(SIGHUP, catch_sig);

	if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		log(my_perror("can't create socket"));
		exit (1);
	}

	init_hash();
	init_database(_PATH_VAR_LOG_QUOTA_STATS);	

	ctrl_access_all();

	while (scanf("%hi %i %i %*i\n", &uid, &sent, &recv) != EOF) {
		if ((uid!=0) && (uid!=IPAU_NOUSER) && ((sent+recv)!=0)) {
			change_user(uid, -(sent+recv), 0);
		}
	}

	ctrl_access_all();
	
	close_database(_PATH_VAR_LOG_QUOTA_STATS);
	if (skfd>0) close(skfd);

	closelog();
}
