# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
import os
import time
import cStringIO
import traceback
import osutil

import pmm_config
import pmmcli_config
import pmmcli_daemon_actions


def stacktrace():
    trace = cStringIO.StringIO()
    traceback.print_exc(file=trace)
    trace_str = trace.getvalue()
    trace.close()
    return trace_str

# Path to the server log file
daemon_log = os.path.join(pmm_config.pmm_logs_directory(), 'pmmcli_daemon.log')

GENERAL = 0
INFO = 2
DEBUG = 4

LOGLEVEL = 4


def log(loglevel, format, *args):
    """Write a message to the daemon log file"""
    if loglevel <= LOGLEVEL:
        try:
            message = format % args
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
            f = open(daemon_log, 'a+')
            f.write('[%s] %s\n' % (timestamp, message))
            f.close()
        finally:
            pass


def log_info(message):
    return log(INFO, "%s", message)


class logger:
    def critical(self, message):
        return log(GENERAL, "%s", message)

    def error(self, message):
        return log(1, "%s", message)

    def info(self, message):
        return log(INFO, "%s", message)

    def debug(self, message):
        return log(DEBUG, "%s", message)


def main():
    log(GENERAL, "Acquire PmmcliDaemon lock")
    mutex = osutil.Interlock(pmm_config.pmmcli_daemon_lock_file())
    if not mutex.lock():
        log(GENERAL, 'PmmcliDaemon lock already locked')
        return False

    try:
        log(GENERAL, "daemon job started")
        daemon_timeout = pmmcli_config.get().get_daemon_timeout()

        while True:
            log(GENERAL, "daemon job delayed for %d minutes" % daemon_timeout)
            time.sleep(daemon_timeout * 60)
            actions = None
            try:
                actions = pmmcli_daemon_actions.ActionItems(log_info)
            except Exception, e:
                log(GENERAL, "exception during action detecting\nStacktrace is:%s", stacktrace())
            try:
                actions.process(log_info)
            except Exception, e:
                log(GENERAL, "exception during action processing\nStacktrace is:%s", stacktrace())
            if not actions.reason():
                # Currently the daemontasks include only dump remove task.
                # The dump remove task should be performed after all Restore Processes are ended
                # This becomes true when reason == 'True'
                processed = True
                try:
                    processed = actions.process_daemontasks(log_info)
                except Exception, e:
                    log(GENERAL, "exception during daemon action processing\nStacktrace is:%s", stacktrace())
                if processed:
                    break
    finally:
        log(GENERAL, "daemon finished job")
        mutex.unlock()

if __name__ == '__main__':
    main()
