#include <errno.h>
#include <fcntl.h>
#include <newt.h>
#include <string.h>
#include <unistd.h>

#include "fs.h"
#include "install.h"
#include "intl.h"
#include "kernel.h"
#include "log.h"
#include "windows.h"

static int copyFile(char * sourceName, char * destName) {
    int source, dest, i;
    char buf[16384];

    logMessage("coping %s to %s\n", sourceName, destName);

    source = open(sourceName, O_RDONLY);
    if (source < 0) {
	newtWinMessage(_("Error"), _("Ok"), 
		       _("file %s missing from source directory"), sourceName);
	return INST_ERROR;
    }

    dest = creat(destName, 0644);
    if (dest < 0) {
	newtWinMessage(_("Error"), _("Ok"), 
			_("failed to create file %s"), destName);
	close(source);
	return INST_ERROR;
    }

    while ((i = read(source, buf, sizeof(buf))) > 0) {
	if (write(dest, buf, i) != i) {
	    newtWinMessage(_("Error"), _("Ok"), 
			   _("error writing to file %s: %s"),
		           destName, strerror(errno));

	    close(source);
	    close(dest);
	    unlink(destName);
	    return 1;
	}
    }

    if (i < 0) {
	newtWinMessage(_("Error"), _("Ok"), 
			_("error reading from file %s: %s"), 
			sourceName, strerror(errno));
    }

    close(source);
    close(dest);
    
    if (i < 0)
	return 1;

    return 0;
}

int kernelCopy(char * filename) {
    int rc = 0;

    if (!filename) {
	do {
	    newtWinMessage(_("Kernel"), _("Ok"),
			    _("Please insert your boot disk in your first "
			      "disk drive if it's not already present."));
	} while (doMount("fd0", "/tmp/bootdisk", "ext2", 1, 0));

	winStatus(34, 3, _("Kernel"), _("Copying kernel from floppy..."));
	rc = copyFile("/tmp/bootdisk/vmlinux.gz", "/mnt/vmlinux.gz");
	sync();
	newtPopWindow();
    } else {
	winStatus(34, 3, _("Kernel"), _("Copying kernel from floppy..."));
	rc = copyFile(filename, "/mnt/vmlinux.gz");
	sync();
	newtPopWindow();
    }

    return rc;
}