/* $Id: download.c,v 1.6 2009/05/07 21:22:52 imil Exp $ */

/*
 * Copyright (c) 2009 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Emile "iMil" Heitor <imil@NetBSD.org> .
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include "pkg_dry.h"

Dlfile *
download_file(char *url)
{
	/* from pkg_install/files/admin/audit.c */
	Dlfile *file;
	char *p;
	size_t buf_len, buf_fetched;
	ssize_t cur_fetched;
	struct url_stat st;
	fetchIO *f;

	if ((f = fetchXGetURL(url, &st, "")) == NULL)
		errx(EXIT_FAILURE, "could not fetch url: %s: %s",
			url, fetchLastErrString);

	
	if ((p = strrchr(url, '/')) != NULL)
		p++;
	else
		p = (char *)url; /* should not happen */

	if (st.size > SSIZE_MAX - 1)
		err(EXIT_FAILURE, "file is too large");
	
	buf_len = st.size;
	XMALLOC(file, sizeof(Dlfile));
	if ((file->buf = malloc(buf_len + 1)) == NULL)
		err(EXIT_FAILURE, "malloc failed");
	
	printf("\e[2K\e[?25l"); /* clear line */

	buf_fetched = 0;
	while (buf_fetched < buf_len) {		
		cur_fetched = fetchIO_read(f, file->buf + buf_fetched,
			buf_len - buf_fetched);
		if (cur_fetched == 0)
			errx(EXIT_FAILURE, "truncated file");
		else if (cur_fetched == -1)
			errx(EXIT_FAILURE, "failure during fetch of file: %s",
				fetchLastErrString);
		buf_fetched += cur_fetched;

		printf("downloading %s: %.f%%\r", p,
			((float)buf_fetched / (float)buf_len) * 100);
	}

	fetchIO_close(f);
	
	file->buf[buf_len] = '\0';
	file->size = buf_len;
	
	if (file->buf[0] == '\0')
		errx(EXIT_FAILURE, "empty download, exiting.\n");

	printf("\n\e[?25h");
	
	return file;
}

