/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package logger

import (
	"bufio"
	"os"
	"path/filepath"

	"github.com/go-logr/logr"
	. "github.com/onsi/gomega"
)

// Provides a log_file that can be used to store the logs generated by clusterctl actions.

// OpenLogFileInput is the input for OpenLogFile.
type OpenLogFileInput struct {
	LogFolder string
	Name      string
}

// OpenLogFile opens a new log file.
func OpenLogFile(input OpenLogFileInput) *LogFile {
	filePath := filepath.Join(input.LogFolder, input.Name)
	Expect(os.MkdirAll(filepath.Dir(filePath), 0750)).To(Succeed(), "Failed to create log folder %s", filepath.Dir(filePath))

	f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) //nolint:gosec // No security issue: filepath is safe.
	Expect(err).ToNot(HaveOccurred(), "Failed to create log file %s", filePath)

	return &LogFile{
		name:   input.Name,
		file:   f,
		Writer: bufio.NewWriter(f),
	}
}

// LogFile is a log file.
type LogFile struct {
	name string
	file *os.File
	*bufio.Writer
}

// Name returns the name of the log file.
func (f *LogFile) Name() string {
	return f.name
}

// Flush flushes the log file.
func (f *LogFile) Flush() {
	Expect(f.Writer.Flush()).To(Succeed(), "Failed to flush log %s", f.name)
}

// Close closes the log file.
func (f *LogFile) Close() {
	f.Flush()
	Expect(f.file.Close()).To(Succeed(), "Failed to close log %s", f.name)
}

// Logger returns a logger that writes to the log file.
func (f *LogFile) Logger() logr.Logger {
	return logr.New(&logger{writer: f})
}
