/* whoopsie
 * 
 * Copyright © 2011-2013 Canonical Ltd.
 * Author: Evan Dandrea <evan.dandrea@canonical.com>
 * 
 * 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; version 3 of the License.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#define _DEFAULT_SOURCE

#include <stdio.h>
#include <syslog.h>
#include <stdarg.h>
#include <time.h>

#include "globals.h"

static int logging_started = 0;
int logging_flags = LOG_PID;

void
log_msg (const char* fmt, ...)
{
    va_list argp;
    struct tm* t;
    char c[9];
    va_start (argp, fmt);

    if (foreground || !logging_started) {
        time_t now = time(NULL);
        t = localtime(&now);
        strftime(c, 9, "%H:%M:%S", t);
        fprintf(stderr, "[%s] ", c);
        vfprintf (stdout, fmt, argp);
        fflush (stdout);
    } else {
        vsyslog(LOG_INFO, fmt, argp);
    }

    va_end (argp);
}

void
open_log (void)
{
    logging_started = 1;
    openlog ("whoopsie", logging_flags, LOG_DAEMON);
}

void
close_log (void)
{
    if (!foreground && logging_started) {
        logging_started = 0;
        closelog ();
    }
}
