2015-05-04 12:04:17 -05:00
|
|
|
package setup
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2015-05-05 12:08:45 -05:00
|
|
|
"strings"
|
2015-05-04 12:04:17 -05:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Startup(c *Controller) (middleware.Middleware, error) {
|
|
|
|
return nil, registerCallback(c, &c.Startup)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Shutdown(c *Controller) (middleware.Middleware, error) {
|
|
|
|
return nil, registerCallback(c, &c.Shutdown)
|
|
|
|
}
|
|
|
|
|
|
|
|
// registerCallback registers a callback function to execute by
|
|
|
|
// using c to parse the line. It appends the callback function
|
|
|
|
// to the list of callback functions passed in by reference.
|
|
|
|
func registerCallback(c *Controller, list *[]func() error) error {
|
|
|
|
for c.Next() {
|
2015-05-05 12:08:45 -05:00
|
|
|
args := c.RemainingArgs()
|
|
|
|
if len(args) == 0 {
|
2015-05-04 12:04:17 -05:00
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
|
2015-05-05 12:08:45 -05:00
|
|
|
nonblock := false
|
|
|
|
if len(args) > 1 && args[len(args)-1] == "&" {
|
|
|
|
// Run command in background; non-blocking
|
|
|
|
nonblock = true
|
|
|
|
args = args[:len(args)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
command, args, err := middleware.SplitCommandAndArgs(strings.Join(args, " "))
|
2015-05-04 12:04:17 -05:00
|
|
|
if err != nil {
|
|
|
|
return c.Err(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn := func() error {
|
|
|
|
cmd := exec.Command(command, args...)
|
2015-05-05 12:20:57 -05:00
|
|
|
cmd.Stdin = os.Stdin
|
2015-05-04 12:04:17 -05:00
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
cmd.Stderr = os.Stderr
|
2015-05-05 12:08:45 -05:00
|
|
|
|
|
|
|
if nonblock {
|
|
|
|
return cmd.Start()
|
|
|
|
}
|
2015-10-09 17:35:34 -05:00
|
|
|
return cmd.Run()
|
2015-05-04 12:04:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
*list = append(*list, fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|