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

#include "devices.h"
#include "install.h"
#include "log.h"
#include "scsi.h"

static int scsiChoicePanel(int * addSCSI);

static int scsiChoicePanel(int * addSCSI) {
    newtComponent label, f, answer;
    newtComponent yes, no;

    newtOpenWindow(21, 7, 35, 9, "SCSI Configuration");

    label = newtLabel(2, 2, "Do you have any SCSI adapters?");
 
    yes = newtButton(5, 5, "Yes");
    no = newtButton(22, 5, "No");

    f = newtForm(NULL, NULL, 0);
    newtFormAddComponents(f, label, yes, no, NULL);
    newtFormSetCurrent(f, no);
    
    answer = newtRunForm(f);
    if (answer == f) 
	answer = newtFormGetCurrent(f);

    newtFormDestroy(f);
    newtPopWindow();

    if (answer == no) 
	*addSCSI = 0;
    else
	*addSCSI = 1;
 
    return 0;
}


int setupSCSIInterfaces(int forceConfig, struct driversLoaded ** dl) {
    int rc;
    int hasscsi;

    if (scsiDeviceAvailable()) return 0;

    do {
	if (forceConfig)
	    forceConfig = 0;
	else {
	    scsiChoicePanel(&hasscsi);
	    if (!hasscsi) return 0;
	}

    	rc = loadDeviceDriver(DRIVER_SCSI, dl);
	if (rc == INST_ERROR) return INST_ERROR;
    } while (rc);

    return 0;
}

int scsiDeviceAvailable(void) {
    int fd;
    char buf[80];
    int i;

    fd = open("/proc/scsi/scsi", O_RDONLY);
    if (fd < 0) {
	logMessage("failed to open /proc/scsi/scsi: %s", strerror(errno));
	return 0;
    }
    
    i = read(fd, buf, sizeof(buf) - 1);
    if (i < 1) {
	logMessage("failed to read /proc/scsi/scsi: %s", strerror(errno));
	return 0;
    }
    close(fd);
    buf[i] = '\0';

    logMessage("/proc/scsi/scsi: %s", buf);

    if (strstr(buf, "devices: none")) {
	logMessage("no scsi devices are available");
	return 0;
    }

    logMessage("scsi devices are available");
    return 1;
}
