/*
 *  dl.c : proof-of-concept URL downloader
 * 
 *  Copyright (c) 2006 by Aaron Griffin <aaronmgriffin@gmail.com>
 * 
 *  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
 *  USA.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>

#include "../download.h"

#define DLBUF_SIZE 512

int download_url(struct url *u)
{
	int nread = 0, nwritten;
	FILE *f = NULL;
	char buffer[DLBUF_SIZE];
	struct url_stat ust;

	downloadTimeout = 10000;

#ifdef DEBUG
	downloadDebug = 1;
#endif

	downloadLastErrCode = 0;

	u->offset = 0;
#ifdef DEBUG
	f = downloadXGet(u, &ust, "pv");
#else
	f = downloadXGet(u, &ust, "p");
#endif

	if(downloadLastErrCode != 0 || f == NULL) {
		fprintf(stderr, "failed to connect to %s: %s\n", u->host, downloadLastErrString);
		return 1;
	}

	while((nread = fread(buffer, 1, DLBUF_SIZE, f)) > 0) {
		printf("read %u bytes\n", nread);
		if(downloadLastErrCode != 0 || ferror(f)) {
			fprintf(stderr, "error downloading %s: %s\n", u->doc, downloadLastErrString);
			fclose(f);
			return 1;
		}

		nwritten = nread;
		while(nwritten < nread) {
			nwritten += fwrite(buffer, 1, (nread - nwritten), stdout);
		}
	}
	fclose(f);

	return 0;
}

int download(char *url) {
	int ret = 0;
	struct url *u;

	u = downloadParseURL(url);

	if(!u) {
		fprintf(stderr, "invalid URL '%s'\n", url);
		exit(1);
	}

	if(strlen(u->scheme) == 0) {
		fprintf(stderr, "warning: scheme not specified, assuming http://\n");
		strcpy(u->scheme, "http");
	}


	ret = download_url(u);
	if(ret != 0) fprintf(stderr, "errors occured\n");

	//downloadFreeURL(u);
	return(ret);
}

int main(int argc, char **argv)
{
	int ret = 0;
	const char *progname;
	int i;

	progname = basename(argv[0]);

	if(argc < 2) {
		fprintf(stderr, "usage: %s <url1> ...\n", progname);
		exit(1);
	}

	for(i = 1; i < argc; i++) {
		ret += download(argv[i]);
	}


	return ret;
}
