#!/usr/bin/python3
"""
@file
@copyright
  SPDX-FileCopyrightText: 2023-2025 European Southern Observatory (ESO) @n
  SPDX-License-Identifier: LGPL-3.0-only
"""

import sys
import signal

from oldbsamp.oldbsamp import OldbSamp


if __name__ == "__main__":
    # SIGNAL handler (for a graceful Ctrl-Break shutdown)
    previous_sigint_handler = signal.getsignal(signal.SIGINT)

    def sigint_handler(signum, frame):
        """
        The procedure works as follows:
        1. New SIGINT signal handler, whose job is to cancel all working threads, is
           installed in the main thread of the main interpreter (SIGINT should work on
           both Linux & Windows).
        2. Upon reception of a SIGINT signal, the new handler does two things:
           a. It cancels all working threads, causing their completion
           b. It reinstalls the previous signal handler for SIGINT
        3. Any subsequent SIGINT will invoke the standard python's handler, which
           ungracefully terminates the application.
        """
        OldbSamp.cancel_sampling()
        OldbSamp.cancel_subscriptions()
        signal.signal(signal.SIGINT, previous_sigint_handler)

    def sigterm_handler(signum, frame):
        OldbSamp.cancel_sampling()
        OldbSamp.cancel_subscriptions()

    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGTERM, sigterm_handler)

    sys.exit(OldbSamp.main())

# __oOo__
