/*
 *  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];

    u->offset = 0;
#ifdef DEBUG
    f = downloadXGet(u, NULL, "v");
#else
    f = downloadXGet(u, NULL, "");
#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 = 0;
        while(nwritten < nread) {
            nwritten += fwrite(buffer, 1, (nread - nwritten), stdout);
        }
    }

    return 0;
}

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

    downloadTimeout = 10000;

#ifdef DEBUG
    downloadDebug = 1;
#endif

    progname = basename(argv[0]);

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

    u = downloadParseURL(argv[1]);

    if(!u) {
        fprintf(stderr, "%s: invalid URL '%s'\n", progname, argv[1]);
        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;
}
