package gokdkly

import (
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/net/context"
)

var (
	terminalSigs = []os.Signal{
		syscall.SIGTERM, // XXX :Should we be treating this as a graceful exit request?
		syscall.SIGHUP,  // XXX: Should we die when we get SIGINT?
		syscall.SIGINT,
	}
)

// ShutdownOnSignals starts a goroutine that invokes cb when any of terminalSigs are received.  If ctx finishes, the
// goroutine will exit.
//
// It's generally a good idea for the callback to log a message and begin whatever graceful shutdown procedure is
// appropriate.  If, after some configurable grace period, the program has still not exited, an error should be logged
// and the program should exit ungracefully.
func ShutdownOnSignals(ctx context.Context, cb func(os.Signal)) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, terminalSigs...)

	go func() {
		select {
		case sig := <-c:
			cb(sig)
		case <-ctx.Done():
			return
		}
	}()
}
