/*
//
// msg.c
//
// Processing messages (informational, warning, and error)
//
// Copyright (c) 1995-96 Jim Nelson.  Permission to distribute
// granted by the author.  No warranties are made on the fitness of this
// source code.
//
*/

#include "htp.h"
#include "option.h"
#include "snprintf.h"

/* symbols used to express severity of message */
const char *severitySymbol[3] =
{
    "[-]",
    "[*]",
    "[!]",
};

void HtpMsg(uint level, STREAM *textFile, const char *format, ...)
{
    va_list argptr;
    char *str;

    /* check severity level */
    if(level < GetOptionValue(OPT_I_MESSAGE))
    {
        return;
    }

    /* allocate room for string ... 1K should be large enough, but a more */
    /* deterministic method would be better */
    if((str = AllocMemory(1024)) == NULL)
    {
        return;
    }

    /* convert variable arguments into single string */
    va_start(argptr, format);
    vsnprintf(str, 1024, format, argptr);
    va_end(argptr);

    /* print the standard message header followed by formatted message */
    printf("%s ", severitySymbol[level]);
    if(textFile != NULL)
    {
        printf("%s line %d: ", textFile->name, textFile->lineNumber);
    }
    printf("%s\n", str);

    /* free the string and exit */
    FreeMemory(str);
}

#if DEBUG
FILE *debugMsgFile = NULL;

void DebugInit(const char *debugMsgFilename)
{
    remove(debugMsgFilename);
    debugMsgFile = fopen(debugMsgFilename, "at");

    if(debugMsgFile == NULL)
    {
        printf("htp: unable to open debug file \"%s\", aborting\n",
            debugMsgFilename);
        exit(1);
    }
}

void DebugTerminate(void)
{
    if(debugMsgFile != NULL)
    {
        fclose(debugMsgFile);
        debugMsgFile = NULL;
    }
}

/*
// DebugMsg
//
// DebugMsg is a helper function to (a) log a formatted string to disk and
// (b) display the same string to the screen.  This function is called by
// DEBUG_PRINT, which is normally removed from the code in a final release
// build.
//
// Because this debug information is really most useful when the program
// is coughing up blood, this function will flush contents every time,
// doing whatever it can to get the debug string to disk.  Slow, but that's
// what a debug build is for.
//
// Important: this file can't use the abstraction present in textfile.c
// because *that* module uses DEBUG_PRINT as well ... (same for suballoc.c
// functions)
//
*/
void DebugMsg(const char *format, ...)
{
    va_list argptr;
    char *str;

    /* 1K should be enough, but no guarantees */
    if((str = malloc(1024)) == NULL)
    {
        /* !! gaaak */
        return;
    }

    /* convert variable arguments into single string */
    va_start(argptr, format);
    vsnprintf(str, 1024, format, argptr);
    va_end(argptr);

    /* write the string to disk */
    fprintf(debugMsgFile, "%s", str);

    /* flush it out to disk */
    fflush(debugMsgFile);

#if 0
    /* write it to screen */
    printf(str);
#endif

    free(str);
}

#endif
