package kubelwagen

import (
	"github.com/hanwen/go-fuse/fuse"
	"github.com/hanwen/go-fuse/fuse/nodefs"
	"github.com/sirupsen/logrus"
)

func serveFuse(dir string, req chan RequestCallback, opts WsFsOpts, closer chan bool) error {
	nfs := NewWsFs(opts, req, closer)

	mountOpts := mkMountOpts(opts)
	conn := nodefs.NewFileSystemConnector(nfs.Root(), &nodefs.Options{})

	server, err := fuse.NewServer(conn.RawFS(), dir, mountOpts)
	if err != nil {
		logrus.Fatalln("cannot mount:", err)
	}
	defer server.Unmount()
	go server.Serve()
	<-closer
	return nil
}

func mkMountOpts(opts WsFsOpts) *fuse.MountOptions {
	var fusermountopts []string
	if opts.NonEmpty {
		fusermountopts = append(fusermountopts, "nonempty")
	}
	mountOpts := &fuse.MountOptions{
		Options: fusermountopts,
		FsName:  "kubelwagen",
		Name:    "wsfs",
	}
	return mountOpts
}
