#!/usr/bin/python
# -*- coding: utf-8 -*-


import os
import sys

import kobo.exceptions
import kobo.conf
import kobo.worker.main
import kobo.worker.tasks

# assuming all tasks are in {{ project_name }}/tasks/task_*.py modules
import tasks


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(tasks, prefix="task_")

    # configuration
    config_file = os.environ.get("{{ project_name|upper }}_CONFIG_FILE", "/etc/{{ project_name }}.conf")
    conf = kobo.conf.PyConfigParser()
    try:
        conf.load_from_file(config_file)
    except (IOError, TypeError):
        sys.stderr.write("\n\nError: The config file was not found.\n")
        return 2

    try:
        kobo.worker.main.main(conf)
    except KeyboardInterrupt:
        sys.stderr.write("\n\nExiting on user cancel.\n")
        return 1
    except kobo.exceptions.ImproperlyConfigured, ex:
        sys.stderr.write("\n\nImproperly configured: " + str(ex) + "\n")
        return 3
    except IOError, ex:
        sys.stderr.write("\n\nIO Error: " + str(ex) + "\n")
        return 4


if __name__ == "__main__":
    sys.exit(main())
