#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lib.h"
#include "lprintf.h"
#include "tcplib.h"
#include "pop.h"

#include "defines.h"

static int isdebug = FALSE;
int pop_ok(Chan *c, char *reason)
{
	if (!tcp_readline(c,reason,BFSZ-1)) return FALSE;
	if (isdebug) printf("<-- %s\n",reason);
	if (reason[0]=='+') return TRUE;
	return FALSE;
}
int pop_login(Chan *c, char *user, char *pass, char *host, char *reason)
{
	int port=110;
	char bf[BFSZ];
	char *s;
	char rhost[BFSZ];
	ncpy(rhost,host,BFSZ-1);
	s = strchr(rhost,':');
	if (s!=NULL) {
		*s = 0;
		port = atoi(s+1);
	}
	if (!tcp_open(c,rhost,port,"")) {
		lprintf(reason,200,"Unable to open port, %s %s:%d",tcp_error(c,bf),rhost,port);
		goto failed;
	}
	if (!pop_ok(c,reason)) goto failed;
	tcp_printf(c,"USER %s\r\n",user);
	if (isdebug) printf("USER %s\n",user);
	if (!pop_ok(c,reason)) goto failed;
	tcp_printf(c,"PASS %s\r\n",pass);
	if (!pop_ok(c,reason)) goto failed;
	return TRUE;
failed:	return FALSE;
}
int pop_readmsg(Chan *c, char *msg, int maxlen, char *reason)
{
	char *s;
	int failed=FALSE;
	int isnulls=FALSE;
	int isend = FALSE;
	int len=0;
	int mlen=0;
	int tot=0;
	strcpy(reason,"None");
	for (;!isend;) { /* 1200 = wait about 20 minutes for data to arrive */
		s = tcp_read_dot(c,&len,&isend,&isnulls,1200,tot==0);
		if (s==NULL) { failed = TRUE; break;}
		if (len>0) {
			if (tot+len<maxlen) {
				strncpy(msg+mlen,s,len);
				mlen += len;
			}
			tot += len;
		}
	}
	msg[mlen] = 0;
	if (failed) return FALSE;
	return TRUE;
}

