package cgi

import (
	"context"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/gopher"
	"tildegit.org/tjp/sliderule/gopher/gophermap"
)

// GopherCGIDirectory runs any executable files relative to a root directory on the file system.
//
// It will also find and run any executables part way through the path, so for example
// a request for /foo/bar/baz can also run an executable found at /foo or  /foo/bar. In
// such a case the PATH_INFO environment variable will include the remaining portion of
// the URI path.
func GopherCGIDirectory(fsroot, urlroot, cmd string, settings *gophermap.FileSystemSettings) sr.Handler {
	if settings == nil || !settings.Exec {
		return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response { return nil })
	}

	handler := cgiDirectory(gopher.ServerProtocol, fsroot, urlroot, cmd)
	return gophermap.ExtendMiddleware(fsroot, urlroot, settings)(handler)
}