/*
 * @(#)Support.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "Support.h"

void skipBytes(FILE *inStream, int bytesToSkip) {
	while (bytesToSkip > 0) {
		char buf[16*1024];
		int n = fread(buf, 1,
			min(bytesToSkip, sizeof buf), inStream);
		if (feof(inStream))
			break;
		bytesToSkip -= n;
	}
}

boolean
toBoolean(const char *str) {
	// skip initial whitespace
	while (*str == '\t' || *str == ' ')
		str++;

	// ignore trailing whitespace
	const char *str2 = str + strlen(str);
	while (str2 > str && (*str2 == '\t' || *str2 == ' '))
		str2--;
	int n = str2 - str;
	char str3[n + 1];
	strncpy(str3, str, n);
	str3[n] = 0;

	if (strcasecmp(str3, "1") == 0
		|| strcasecmp(str3, "on") == 0
		|| strcasecmp(str3, "true") == 0)
		return true;
	else
	if (strcasecmp(str3, "0") == 0
		|| strcasecmp(str3, "off") == 0
		|| strcasecmp(str3, "false") == 0)
		return false;
	else
		throw new Exception("invalid boolean");
}

void
makeDirs(const char *fileName) {
	char str[1024];
	int i = 0;
	while (1) {
		for (; fileName[i] != 0 && fileName[i] != '/'; i++)
			str[i] = fileName[i];
		str[i] = 0;

		if (fileName[i] == 0)
			break;

		mkdir(str, S_IRWXU);
		str[i++] = '/';
	}
}

int
waitForInput(FILE *inStream, int seconds) {
	fd_set fdSet;
	FD_ZERO(&fdSet);
	FD_SET(fileno(inStream), &fdSet);

	struct timeval timeout;
	timeout.tv_sec = seconds;
	timeout.tv_usec = 0;

	int res;
	do {
 		res = select(FD_SETSIZE, &fdSet, NULL, NULL, &timeout);
	} while (res == -1L && errno == EINTR);

	return res;
}
