/*

Copyright (C) 2015-2018 Olaf Till <i7tiol@t-online.de>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.

*/

#ifndef __OCT_PARALLEL_SIGHANDLER__

#define __OCT_PARALLEL_SIGHANDLER__

#include <signal.h> // for SIG... definitions, everything else
                    // regarding signal handling is dealt with by
                    // linked (or inlined) C-code and potentially
                    // provided by gnulib

class
inthandler_dont_restart_syscalls
{
public:
  inthandler_dont_restart_syscalls (void)
  : restore_int (false), restore_break (false)
#ifdef SIGINT
    , newintaction (NULL), oldintaction (NULL)
#endif
#ifdef SIGBREAK
    , newbreakaction (NULL), oldbreakaction (NULL)
#endif
  {
#ifdef SIGINT
    newintaction = gnulib_alloc_sigaction ();

    oldintaction = gnulib_alloc_sigaction ();

    if (gnulib_getsigaction (SIGINT, oldintaction))
      return;

    restore_int = true;

    gnulib_copy_sigaction (newintaction, oldintaction);

    gnulib_remove_sa_restart (newintaction);

    gnulib_setsigaction (SIGINT, newintaction);
#endif

#ifdef SIGBREAK
    newbreakaction = gnulib_alloc_sigaction ();

    oldbreakaction = gnulib_alloc_sigaction ();

    if (gnulib_getsigaction (SIGBREAK, oldbreakaction))
      return;

    restore_break = true;

    gnulib_copy_sigaction (newbreakaction, oldbreakaction);

    gnulib_remove_sa_restart (newbreakaction);

    gnulib_setsigaction (SIGBREAK, newbreakaction);
#endif
  }

  ~inthandler_dont_restart_syscalls (void)
  {
#ifdef SIGINT
    if (restore_int)
      gnulib_setsigaction (SIGINT, oldintaction);

    free (newintaction);

    free (oldintaction);
#endif

#ifdef SIGBREAK
    if (restore_break)
      gnulib_setsigaction (SIGBREAK, oldbreakaction);

    free (newbreakaction);

    free (oldbreakaction);
#endif
  }

private:

  bool restore_int;

  bool restore_break;

#ifdef SIGINT
  void *newintaction;

  void *oldintaction;
#endif

#ifdef SIGBREAK
  void *newbreakaction;

  void *oldbreakaction;
#endif
};

#endif // __OCT_PARALLEL_SIGHANDLER__
