package lockingwriter

import (
	"os"
	"time"

	"github.com/gofrs/flock"
)

// for now this package defines a writer for use with log.New(). It it intended to be used from the external ssh applications. This logger uses a file lock to allow all the various ssh applications to log to the same file.

type LockingWriter struct {
	path string
}

const fp = "/town/var/log/external.log"

func NewLockingWriter() *LockingWriter {
	f, err := os.Create(fp)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	return &LockingWriter{
		path: fp,
	}
}

func (l *LockingWriter) Write(p []byte) (n int, err error) {
	fl := flock.New(l.path)

	var locked bool
	for !locked {
		locked, err = fl.TryLock()
		if err != nil {
			return
		}
		time.Sleep(time.Second)
	}
	var f *os.File
	f, err = os.OpenFile(l.path, os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		return
	}

	defer f.Close()
	defer fl.Unlock()

	return f.Write(p)
}
