#!/usr/bin/python3
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: Copyright contributors to the OpenScanHub project.

import sys

import kobo.conf
import kobo.exceptions
import kobo.worker.main
import kobo.worker.tasks
from kobo.worker.taskmanager import TaskManager

# assuming all tasks are in osh/worker/tasks/task_*.py modules
import osh.worker.tasks
from osh.common.conf import get_config_dict


# override the `foreground` task attribute if RUN_TASKS_IN_FOREGROUND is set in worker.conf
class OSHTaskManager(TaskManager):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.conf.get("RUN_TASKS_IN_FOREGROUND"):
            for task in self.task_container:
                self.task_container[task].foreground = True


def main():
    # register generic kobo tasks
    kobo.worker.main.TaskContainer.register_module(kobo.worker.tasks, prefix="task_")
    # register project specific tasks
    kobo.worker.main.TaskContainer.register_module(osh.worker.tasks, prefix="task_")

    # configuration
    conf = get_config_dict(config_env="OSH_WORKER_CONFIG_FILE",
                           config_default="/etc/osh/worker.conf")
    if conf is None:
        sys.exit(2)

    try:
        kobo.worker.main.main(conf, None, OSHTaskManager)
    except KeyboardInterrupt:
        print("\n\nExiting on user cancel.", file=sys.stderr)
        sys.exit(1)
    except kobo.exceptions.ImproperlyConfigured as ex:
        print("\n\nImproperly configured:", ex, file=sys.stderr)
        sys.exit(3)
    except OSError as ex:
        print("\n\nIO Error:", ex, file=sys.stderr)
        sys.exit(4)


if __name__ == "__main__":
    main()
