/* debug.c - Debugging primitives
 *
 * Copyright (c) 2003 Peter Busser <peter@trusteddebian.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, USA
 */

#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <syslog.h>
#include <stdlib.h>

#include "debug.h"


/* Local variables */
/* This variable controls the output of debugging messages
 * A value of DEBUG_ON enables debugging output
 * A value of DEBUG_OFF disables debugging output
 * The default is no debugging output
 * The value can be changed using the set_debug() function.
 */
static enum debugval debugstate = DEBUG_OFF;


/* Set debugging */
void set_debug( enum debugval val )
{
	assert( ((val == DEBUG_OFF) || (val == DEBUG_ON)) );

	if( (val == DEBUG_OFF) || (val == DEBUG_ON) ) {
		debugstate = val;
	}
}

/* Print a debug message to stderr
 *
 * This piece of code was derived from a code in the vsnprintf man page
 */
void debug( const char *fmt, ... )
{
	/* Guess we need no more than 100 bytes. */
	int n;
	size_t size;
	char *buf;
	va_list ap;

	size = 100;

	/* Do not print any message when debugging is turned off */
	if( debugstate == DEBUG_OFF ) {
		return;
	}

	buf = malloc( size );
	if( buf == NULL ) {
		fprintf( stderr, "Out of memory\n" );
		exit( 1 );
	}

	for(;;) {
		/* Try to print in the allocated space. */
		va_start( ap, fmt );
		n = vsnprintf( buf, size, fmt, ap );
       		va_end( ap );

		/* If that worked, stop. */
		if( n > -1 && n < size ) {
			break;
		}

		/* Else try again with more space. */
		if( n > -1 ) {
			/* glibc 2.1 */
			/* Precisely what is needed */
			size = n + 1;
		} else {
			/* glibc 2.0 */
			/* Twice the old size */
			size *= 2;
		}

		buf = realloc( buf, size );
		if( buf == NULL) {
			fprintf( stderr, "Out of memory\n" );
			exit( 1 );
		}
	}

	/* Output the message to stdout */
	debugstr( buf );

	free( buf );
}


/* Print a debugging string */
void debugstr( const char *str )
{
	/* Only print if debugging is enabled */
	if( debugstate == DEBUG_ON ) {
		syslog( LOG_INFO, str );
	}
}

