// Copyright (C) 2019 Marius Schellenberger

package log

import (
	"git.giftfish.de/ston1th/godrop/v2"
	"git.giftfish.de/ston1th/gowiki/pkg/core"
	stdlog "log"
	"os"
	"path/filepath"
)

var (
	log   = stdlog.New(os.Stdout, "", stdlog.LstdFlags)
	debug = false
)

func Stderr() {
	log = stdlog.New(os.Stderr, "", stdlog.LstdFlags)
}

func InitLogger(cfg core.Config) {
	debug = cfg.Debug
	if cfg.LogFile == "-" {
		return
	}
	logfile := filepath.Join(cfg.DataDir, cfg.LogFile)
	err := godrop.Unveil(logfile, "rwc")
	if err != nil {
		stdlog.Fatal(err)
		return
	}
	f, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640)
	if err != nil {
		stdlog.Fatal(err)
	}
	stdlog.SetOutput(f)
	log = stdlog.New(f, "", stdlog.LstdFlags)
}

func Println(v ...interface{}) {
	log.Println(v...)
}

func Printf(fmt string, v ...interface{}) {
	log.Printf(fmt, v...)
}

func Fatal(v ...interface{}) {
	log.Fatal(v...)
}

func Debug(v ...interface{}) {
	if debug {
		log.Println(append([]interface{}{"debug:"}, v...)...)
	}
}

func Debugf(fmt string, v ...interface{}) {
	if debug {
		log.Printf("debug: "+fmt, v...)
	}
}
