////////////////////////////////////////////////////////////////////////////////
// 
// Signal.hh 
//
//    produced: 2024-04-11 jr
//
////////////////////////////////////////////////////////////////////////////////
#ifndef SIGNAL_HH
#define SIGNAL_HH

#include <iostream>

#include <csignal>
#include "CommandlineOptions.hh"

extern "C" void topcom_signalhandler(int signalno);

namespace topcom {

  class Signal {
  private:
    static constexpr int              _maxrepeat = 1;
    static volatile std::sig_atomic_t _signalno;
    static volatile std::sig_atomic_t _repeatcounter;
  public:
    inline static void signalhandler(int signalno) {
      _signalno = signalno;
      ++_repeatcounter;
      if ((_signalno == SIGINT) && (_repeatcounter > _maxrepeat)) {
	signal(SIGINT, SIG_DFL);
	raise(SIGINT);
      }
    }

    inline static void init() {
      MessageStreams::verbose() << "initializing signal handling" << std::endl;
      signal(SIGINT, topcom_signalhandler);
      signal(SIGTERM, topcom_signalhandler);
    }

    inline static bool signal_received() {
      return _signalno != 0;
    }

    inline static std::sig_atomic_t signalno() {
      return _signalno;
    }

    inline static int exit_value() {
      if (_signalno != 0) {
	return _signalno + 128;
      }
      else {
	return 0;
      }
    }
  };

}; // namespace topcom



#endif

// eof Signal.hh
