package gonix

/*
#include <syslog.h>
void
callsyslog(int prio, const char *msg)
{
    syslog(prio, "%s", msg);
}
*/
import "C"

import (
	"bytes"
	"io"
	"log/syslog"
	"unsafe"
)

type logFilter struct {
}

func (lf *logFilter) Write(msg []byte) (int, error) {
	msglen := len(msg)
	for i := 0; i < len(msg); i++ {
		if msg[i] >= '0' && msg[i] <= '9' {
			continue
		}
		if msg[i] == ' ' || msg[i] == '/' || msg[i] == ':' {
			continue
		}
		msg = msg[i:]
		break
	}
	var prio C.int
	switch {
	case bytes.HasPrefix(msg, []byte("DEBUG ")):
		prio = C.LOG_DEBUG
	case bytes.HasPrefix(msg, []byte("INFO ")):
		prio = C.LOG_INFO
	case bytes.HasPrefix(msg, []byte("WARN ")):
		prio = C.LOG_WARNING
	case bytes.HasPrefix(msg, []byte("ERROR ")):
		prio = C.LOG_ERR
	default:
		prio = C.LOG_NOTICE
	}
	C.callsyslog(prio, (*C.char)(unsafe.Pointer(&msg[0])))
	return msglen, nil
}

func OpenLog(name string, facility syslog.Priority) io.Writer {
	ident := C.CString(name)
	C.openlog(ident, C.LOG_NDELAY|C.LOG_PID, C.int(facility))
	return new(logFilter)
}
