//go:build !windows

/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/

package logger

import (
	"log/syslog"
	"os"
	"syscall"
)

type linuxSyslog struct {
	writer *syslog.Writer
}

func (l *linuxSyslog) WriteLog(logLevel LogLevel, message string) error {
	switch logLevel {
	case LogLevelInfo:
		return l.writer.Info(message)
	case LogLevelCrit:
		return l.writer.Crit(message)
	case LogLevelErr:
		return l.writer.Err(message)
	case LogLevelWarn:
		return l.writer.Warning(message)
	case LogLevelDebug:
		return l.writer.Debug(message)
	default:
		return l.writer.Info(message)
	}
}

func (l *linuxSyslog) Close() error {
	return l.writer.Close()
}

func NewSystemLogger() (SystemLogger, error) {
	writer, err := syslog.New(syslog.LOG_WARNING|syslog.LOG_DAEMON, "jobarranger2")
	if err != nil {
		return nil, err
	}
	return &linuxSyslog{writer: writer}, nil
}

// Mutex locker
type linuxMutexLocker struct {
}

func (ml *linuxMutexLocker) LockFile(f *os.File) error {
	// Multi-process mutex lock
	return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
}

func (ml *linuxMutexLocker) UnlockFile(f *os.File) error {
	// Multi-process mutex lock
	return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
}

func NewMutexLocker() (MutexLocker, error) {
	return &linuxMutexLocker{}, nil
}
