package main

import (
	"log"
	"os"

	"code.justin.tv/release/trace/internal/pipeline"
	"code.justin.tv/release/trace/internal/sink"
	"golang.org/x/net/context"
)

const (
	filePerm = 0644
	fileFlag = os.O_CREATE | os.O_EXCL | os.O_WRONLY
)

func newFileSink(ctx context.Context, filename string) (sink.Sink, error) {
	file, err := os.OpenFile(filename, fileFlag, filePerm)
	if err != nil {
		return nil, err
	}

	// On errors, log the error, then shut down
	logger := log.New(os.Stderr, "[filesink] ", log.LstdFlags|log.Lmicroseconds)
	logErrors := pipeline.LogErrors(logger)
	abortErrors, ctx := pipeline.AbortOnError(ctx)
	onError := pipeline.CombinedHandler(logErrors, abortErrors)

	return sink.WriterSink(ctx, file, onError), nil
}
