# w.c.s. - web application for online forms
# Copyright (C) 2005-2014  Entr'ouvert
#
# 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 2 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 tempfile
import time
import os

from django.core.management.base import BaseCommand
from qommon.publisher import get_publisher_class

from qommon.vendor import locket
from qommon.cron import cron_worker


class Command(BaseCommand):
    help = 'Execute cronjobs'

    def handle(self, verbosity, **options):
        with locket.lock_file(os.path.join(tempfile.gettempdir(), 'wcs-cron')):
            now = time.localtime()
            publisher_class = get_publisher_class()
            publisher_class.register_cronjobs()
            publisher = publisher_class.create_publisher()
            app_dir = publisher.app_dir
            for hostname in publisher.get_tenants():
                publisher.app_dir = os.path.join(app_dir, hostname)
                cron_worker(publisher, now)
