// Copyright (C) MongoDB, Inc. 2014-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

package signals

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

	"github.com/mongodb/mongo-tools/common/log"
	"github.com/mongodb/mongo-tools/common/util"
)

// Handle is like HandleWithInterrupt but it doesn't take a finalizer and will
// exit immediately after the first signal is received.
func Handle() chan struct{} {
	return HandleWithInterrupt(nil)
}

// HandleWithInterrupt starts a goroutine which listens for SIGTERM, SIGINT, and SIGKILL. It also
// calles signal.Ignore to explicitly ignore SIGPIPE. It calls the finalizer function when the first
// signal is received and forcibly terminates the program after the second. If a nil function is
// provided, the program will exit after the first signal.
func HandleWithInterrupt(finalizer func()) chan struct{} {
	// Ignore SIGPIPE synchronously so there is no race between this call and the first write: a
	// broken pipe must surface as an EPIPE write error, not kill the process.
	signal.Ignore(syscall.SIGPIPE)

	finishedChan := make(chan struct{})
	go handleSignals(finalizer, finishedChan)
	return finishedChan
}

func handleSignals(finalizer func(), finishedChan chan struct{}) {
	log.Logv(log.DebugLow, "will listen for SIGTERM and SIGINT")
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
	defer signal.Stop(sigChan)
	if finalizer != nil {
		select {
		case sig := <-sigChan:
			// first signal use finalizer to terminate cleanly
			log.Logvf(log.Always, "signal '%s' received; attempting to shut down", sig)
			finalizer()
		case <-finishedChan:
			return
		}
	}
	select {
	case sig := <-sigChan:
		// second signal exits immediately
		log.Logvf(log.Always, "signal '%s' received; forcefully terminating", sig)
		os.Exit(util.ExitFailure)
	case <-finishedChan:
		return
	}
}
