#!/usr/bin/python -tt
# -*- 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 {{ project_name }}.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({{ project_name }}.tasks, prefix="task_")

    # configuration
    config_env = "{{ project_name|upper }}_CONFIG_FILE"
    config_default = "/etc/{{ project_name }}.conf"
    config_file = os.environ.get(config_env, config_default)
    conf = kobo.conf.PyConfigParser()
    try:
        conf.load_from_file(config_file)
    except (IOError, TypeError):
        sys.stderr.write("\n\nError: The config file '%s' was not found.\nCreate the config file or specify the '%s'\nenvironment variable to override config file location.\n" % (config_default, config_env))
        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: %s\n" % ex)
        return 3
    except IOError, ex:
        sys.stderr.write("\n\nIO Error: %s\n" % ex)
        return 4


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