#!python
"""
Copyright (C) 2020  Universite catholique de Louvain, Belgium.

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/>.
"""

import signal
import sys
import traceback

from SlurmDagman.process.command.arguments import options
from SlurmDagman.process.worker import Worker


SLURM_DAGMAN_WORKER = None


def init():
    global SLURM_DAGMAN_WORKER
    try:
        SLURM_DAGMAN_WORKER = Worker(options['dag_file'], options['outfile'], options['proxy_file'], options['sleep_time'], options['max_jobs_queued'], options['max_jobs_submit'], options['submit_wait_time'])
    except Exception:
        print('Error running slurm_dagman:\n%s' % (traceback.format_exc()))
        sys.exit(1)


def run():
    if isinstance(SLURM_DAGMAN_WORKER, Worker):
        try:
            return SLURM_DAGMAN_WORKER.run()
        except Exception:
            print('Error running slurm_dagman:\n%s' % (traceback.format_exc()))
            return 1
    else:
        print('Unexpected type of slurm dagman worker object:\n%s' % (traceback.format_exc()))
        sys.exit(1)


def terminate():
    if isinstance(SLURM_DAGMAN_WORKER, Worker):
        try:
            SLURM_DAGMAN_WORKER.terminate()
        except Exception:
            print('Error terminating slurm dagman worker:\n%s' % (traceback.format_exc()))
        try:
            SLURM_DAGMAN_WORKER.write_rescue_dag_file()
        except Exception:
            print('Failed to write rescue DAG:\n%s' % (traceback.format_exc()))
    else:
        print('Unexpected type of slurm dagman worker object:\n%s' % (traceback.format_exc()))


if __name__ == '__main__':

    def signal_term_handler(signum, frame):
        print('Got SIGTERM (%s) signal:' % (signum))
        print(' -> Terminating...')
        terminate()
        print('Terminated.')
        sys.exit(0)
    signal.signal(signal.SIGTERM, signal_term_handler)

    init()
    rc = run()
    if rc > 0:
        terminate()
    sys.exit(rc)
