# -*- coding: utf-8 -*-

# Copyright (c) 2015, Thierry Lemeunier <thierry at lemeunier dot net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this 
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Provides a simple Daemon class to ease the process of forking a
python application on POSIX systems.
"""

import errno
import logging
import socket
from logging.handlers import RotatingFileHandler
import os
import signal
import sys
import time
import datetime

from ...server.util.Configuration import Configuration


class Daemon(object):
    """Daemon base class"""

    def run(self):
        """Override. We are in the daemon at this point."""

    def main(self):
        """Read the command line and either start or stop the daemon"""
        if Configuration.action == 'start':
            self.start()
        elif Configuration.action == 'stop':
            self.stop()
        elif Configuration.action == 'status':
            self.status()
        else:
            raise ValueError(Configuration.action)

    def on_sigterm(self, signalnum, frame):
        """Handle segterm by treating as a keyboard interrupt"""
        raise KeyboardInterrupt('SIGTERM')

    def add_signal_handlers(self):
        """Register the sigterm handler"""
        signal.signal(signal.SIGTERM, self.on_sigterm)

    def start(self):
        """Initialize and run the daemon"""
        self.check_pid()
        self.add_signal_handlers()
        self.start_logging()

        try:
            self.check_pid_writable()
            self.check_server_accessibility()
            self.daemonize()
        except:
            logging.exception("failed to start due to an exception")
            raise

        self.write_pid()
        try:
            try:
                self.run()
            except (KeyboardInterrupt, SystemExit):
                pass
            except OSError as exc: