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

"""
| This file is part of the web2py Web Framework
| Created by Attila Csipa <web2py@csipa.in.rs>
| Modified by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)

Cron-style interface
"""

import sys
import os
import threading
import logging
import time
import sched
import re
import datetime
import platform
import portalocker
import fileutils
import cPickle
from gluon.settings import global_settings

logger = logging.getLogger("web2py.cron")
_cron_stopping = False
_cron_subprocs = []


def absolute_path_link(path):
    """
    Returns an absolute path for the destination of a symlink

    """
    if os.path.islink(path):
        link = os.readlink(path)
        if not os.path.isabs(link):
            link = os.path.join(os.path.dirname(path), link)
    else:
        link = os.path.abspath(path)
    return link


def stopcron():
    "Graceful shutdown of cron"
    global _cron_stopping
    _cron_stopping = True
    while _cron_subprocs:
        _cron_subprocs.pop().terminate()

class extcron(threading.Thread):

    def __init__(self, applications_parent, apps=None):
        threading.Thread.__init__(self)
        self.setDaemon(False)
        self.path = applications_parent
        self.apps = apps
        # crondance(self.path, 'external', startup=True, apps=self.apps)

    def run(self):
        if not _cron_stopping:
            logger.debug('external cron invocation')
            crondance(self.path, 'external', startup=False, apps=self.apps)


class hardcron(threading.Thread):

    def __init__(self, applications_parent):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.path = applications_parent
        crondance(self.path, 'hard', startup=True)

    def launch(self):
        if not _cron_stopping:
            logger.debug('hard cron invocation')
            crondance(self.path, 'hard', startup=False)

    def run(self):
        s = sched.scheduler(time.time, time.sleep)
        logger.info('Hard cron daemon started')
        while not _cron_stopping:
            now = time.time()
            s.enter(60 - now % 60, 1, self.launch, ())