/*
 * tron: quota checking
 */

char qbuf[5120];
char lnbuf[10];
#include	"tron.h"

ckquotas()
{
	register struct qent *p1, *p2, *p3;
	register short i;
	short ndel = 0;

	if(qopen())
		return(1);

	p1 = &q;
	while((i = read(qd[1], qbuf, 5120)) > 0){
		write(qd[2], qbuf, i);
		for(p2 = qbuf, p3 = &qbuf[i]; p2 < p3; p2++){
			if(p2->q_uid == 0 && p2->q_gid == 0)
				continue;
			strncpy(lnbuf, p2->q_ln, 8);
			lnbuf[8] = 0;
			if(getqent(qd[0], p1, lnbuf) == 0){
				ndel++;
				qvalid(p2);
				continue;
			}
			if(p1->q_dquo != p2->q_dquo){
				if(!inlog(p1->q_ln))
					fprintf(stdout, "*TRON: %.8s disk quota changed from %u to %u\n",
					p2->q_ln, p1->q_dquo, p2->q_dquo);
			}
			if(p1->q_fquo != p2->q_fquo){
				if(!inlog(p1->q_ln))
					fprintf(stdout, "*TRON: %.8s file quota changed from %u to %u\n",
					p2->q_ln, p1->q_fquo, p2->q_fquo);
			}
			if(p1->q_mquo != p2->q_mquo && (p2->q_uid < 10000 ||
				(p2->q_mquo != p1->q_mquo + p1->q_inc*10))){
				if(!inlog(p1->q_ln))
					fprintf(stdout, "*TRON: %.8s money quota changed from %u to %u\n",
					p2->q_ln, p1->q_mquo, p2->q_mquo);
			}
			if(p1->q_flg != p2->q_flg){
				if(!inlog(p1->q_ln))
					fprintf(stdout, "*TRON: %.8s flags changed from %o to %o\n",
					p2->q_ln, p1->q_flg, p2->q_flg);
			}
		}
	}
	for(i = 0; i < 3; i++)
		close(qd[i]);
	unlink(QUODAT);
	link(QUOTMP, QUODAT);
	unlink(QUOTMP);
	chown(QUODAT, 3, 3);
	if(ndel)
		fprintf(stdout, "TRON: %d new people in quota list\n", ndel);
}

qvalid(pq)
register struct qent *pq;
{
	register short flg;

	flg = 0;
	if(pq->q_uid < 10000){
		if(pq->q_fquo != 100 ||
			pq->q_dquo != 500)flg++;
	} else	if(pq->q_fquo != 50 || pq->q_dquo != 200) flg++;
	if(flg){
		if(!inlog(pq->q_ln))
			fprintf(stdout, "*TRON: Non-standard quota for %.8s %u/%u Uid=%d\n",
			pq->q_ln, pq->q_dquo, pq->q_fquo, pq->q_uid);
	}
}

qopen()
{
	if((qd[0] = open(QUODAT, 0)) == -1){
		fprintf(stdout, "*TRON: Can't open %s (quota)\n", QUODAT);
		return(-1);
	}
	if((qd[1] = open(QUOFILE, 0)) == -1){
		close(qd[0]);
		fprintf(stdout, "**TRON: Can'T open quofile %s\n", QUOFILE);
		return(-1);
	}
	if((qd[2] = creat(QUOTMP, 0600)) == -1){
		close(qd[0]);
		close(qd[1]);
		fprintf(stdout, "***TRON: Can't create quota temp file %s\n", QUOTMP);
		return(-1);
	}
	return(0);
}

