/* errors.c -- print error messages for ttywatch
 *
 * Copyright © 2000, 2001 Michael K. Johnson <a1237+ttywatch@danlj.org>
 *
 * 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 <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>

#include "errors.h"

void
warn(machine *m, char *warning, ...) {
    char *format, *message;
    int req = 100, size;
    va_list ap;

    if (m) {
	format = alloca(strlen(warning) + strlen(m->name) + 15);
	sprintf(format, "ttywatch[%s]: %s\n", m->name, warning);
    } else {
	format = alloca(strlen(warning) + 15);
	sprintf(format, "ttywatch: %s\n", warning);
    }

    va_start(ap, warning);
    message = malloc(req);
    while (1) {
	size = vsnprintf (message, req, format, ap);
	if (size > -1 && size < req) break; /* yay, it worked */
	if (size > -1) req = size+1;
	else req *= 2;
	message = realloc(message, req);
    }
    va_end(ap);

    write(STDERR_FILENO, message, size);
    if (m && (m->log_fd >= 0)) write(m->log_fd, message, size);
}

void
die(char *warning, ...) {
    char *message;
    int req = 100, size;
    va_list ap;

    va_start(ap, warning);
    message = malloc(req);
    while (1) {
	size = vsnprintf (message, req, warning, ap);
	if (size > -1 && size < req) break; /* yay, it worked */
	if (size > -1) req = size+1;
	else req *= 2;
	message = realloc(message, req);
    }
    va_end(ap);

    write(STDERR_FILENO, message, size);
    exit (1);
}

