#!/usr/bin/env python

import os
import sys
# import signal
import pyaml
import time
import logging
import logging.handlers
import syslog
import daemon
import daemon.runner
from cronify import cronify

CFG_FILE = "/etc/cronify.yaml"
PID_FILE = "/var/run/cronify.pid"
_LOG_DIR = "/var/log/cronify"
LOG_FILE = os.path.sep.join([_LOG_DIR, "cronify.log"])

try:
    os.mkdir(_LOG_DIR)
except OSError, e:
    if e.errno == 13:
        sys.stderr.write("No permissions to create log dir %s\n" % (_LOG_DIR,))
        sys.exit(1)

def start_watcher():
    """Read config file, start watcher and return Watcher object"""
    cfg_fileh = open(CFG_FILE, 'r')
    data = pyaml.yaml.load(cfg_fileh)
    cfg_fileh.close()
    syslog.syslog("Cronify daemon starting..")
    return cronify.Watcher(data)

def testy():
    """Small fake function to test daemon app with"""
    while 1:
        syslog.syslog('Running..')
        time.sleep(5)

class CronifyDaemon(object):

    """Cronify daemon application class.
    Used with daemon.runner.DaemonRunner"""

    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/null'
        self.stderr_path = '/dev/tty'
        self.pidfile_path = PID_FILE
        self.pidfile_timeout = 5
        self.watcher = None

    def __del__(self):
        """Cleanup sanely if watchers are started"""
        if self.watcher:
            self.watcher.cleanup()

    def setup_logger(self):
        """Instantiate our loggers"""
        loggers = [logging.getLogger('cronify.cronify'), logging.getLogger('cronify.threadpool')]
        _handler = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when = "midnight", interval = 1, backupCount = 7)
        log_format = logging.Formatter('%(name)s - %(threadName)s - %(asctime)s - %(levelname)s - %(message)s')
        _handler.setFormatter(log_format)
        [logger.addHandler(_handler) for logger in loggers]
        [logger.setLevel(logging.INFO) for logger in loggers]

    def run(self):
        """Startup our watcher and sleep forever (an hour at a time..)"""
        # testy()
        self.setup_logger()
        self.watcher = start_watcher()
        while 1:
            time.sleep(3600)

cronifyd = CronifyDaemon()

if __name__ == "__main__":
    daemon_runner = daemon.runner.DaemonRunner(cronifyd)
    daemon_runner.do_action()
