#include	"quotas.h"
#include	"hsubs.h"

extern	uint	lent;
int	fo;
char buf[512], lin[128];
char	*out;
int	dq, fq, mq;

struct	qent	q, trash;


main(cc,vv)
char **vv;
{
	register char *s, *t, *l;
	int r;

	int fd;
	q.q_fquo = fq = 0;
	q.q_dquo = dq = 0;
	while(--cc){
		vv++;
		if(**vv != '-')break;
		switch(*++*vv){
	case 'd':
		if(cc > 1){
			dq++;
			cc--;
			q.q_dquo = atoi(*++vv);
		}
		break;

	case 'f':
		if(cc > 1){
			fq++;
			cc--;
			q.q_fquo = atoi(*++vv);
		}
		break;

	case 'm':
		if(cc > 1){
			mq++;
			cc--;
			q.q_mquo = atoi(*++vv);
		}
		break;

	default:
		printf("'%c' is an illegal option\n", **vv);
		exit(2);
		}
	}
	if(cc != 2){
		printf("Usage: mkquo [-d diskquo] [-f filequo] [-m moneyquo] passwdlines appendto\n");
		exit(1);
	}
	q.q_fused=q.q_dused=q.q_flg = 0;
	if((fd = open(*vv, 0)) == -1){
		printf("Can not open lines to add file: %s\n", *vv);
		exit(3);
	}
	if((fo = open(out = *++vv, 2)) == -1){
		if((fo = creat(out, 0600)) == -1){
bad:
			printf("Can not open output file %s\n", *vv);
			exit(2);
		}
		lseek(fo, (long)(QSZ)*NHENT, 0);
		lseek(fo, -512L, 1);
		write(fo, buf, 512);
		close(fo);
		if((fo = open(out, 2)) == -1)goto bad;
	}

	t = lin;
	while((r = read(fd,buf,512))>0){
		l = &buf[r];
		s=buf;
		while(s<l){
			if((*t++ = *s++) !='\n')continue;
			*(t-1)=0;
			doit();
			t = lin;
		}
	}
	close(fd);
	close(fo);
	exit(0);
}

doit(){
	register char *s,*t;
	register i;
	s = lin;
	t = q.q_ln;
	while((*t = *s) != ':' && *s)s++,t++;
	if(*s++ == 0)return;
	*t = 0;
	if(getqent(fo, &trash, q.q_ln)){
		printf("Duplicate name already has quota entry: %s (Ignored)\n",
			q.q_ln);
		return;
	}
	i = 0;
	while(*s != ':' && *s)s++;
	if(*s++ == 0)return;
	while(*s >= '0' && *s <= '9')i=i*10+(*s++)-'0';
	if(*s++ == 0)return;
	q.q_uid=i;
	if(fq == 0)
		if(i < 10000)q.q_fquo = 100;
		else q.q_fquo = 50;
	if(dq == 0)
		if(i < 10000)q.q_dquo = 500;
		else q.q_dquo = 200;
	if(mq == 0)
		if(i < 10000)q.q_mquo = 0;
		else	{
			q.q_mquo = INITIALM*10;
			q.q_inc = DEFMONEY;
		}
	i=0;
	while(*s >= '0' && *s <= '9')i=i*10+(*s++)-'0';
	q.q_gid = i;
	if(*s++ == 0)return;
	while(*s && *s != ':')s++;
	if(*s++ == 0)return;
	t = q.q_fs;
	s++;
	while((*t = *s) != '/' && *s != ':' && *s)s++,t++;
	if(*s == 0)return;
	*t = 0;
	lseek(fo, (long)(lent)*QSZ, 0);
	write(fo,&q,sizeof q);
}

