import os
from cherrypy import process
import logging

logger = logging.getLogger('splunk.appserver.lib.custompidfile')


class ProcessID(process.plugins.SimplePlugin):
    """ handles creation and removal of the splunkweb.pid file """

    PID_PATH = ""

    def __init__(self, bus, pid_path):
        self.bus = bus
        self.PID_PATH = pid_path

    def start(self):
        pid = os.getpid()
        logger.debug('"Hello, American investor. I see you are interested in distributing Mr. Sparkle in your home prefecture. You have chosen wisely. But please, don\'t believe me. Observe this commercial."')
        logger.info('Writing pidfile at %s (PID: %s)"' % (self.PID_PATH, pid ) )

        try:
            pidfile = None
            pidfile = open(self.PID_PATH, 'w')
            pidfile.write( str(pid) )
        except (OSError, IOError), fail:
            message = "Unable to write %(path)s. Exiting. [%(fail)s]" % {'path':self.PID_PATH, 'fail':str(fail)}
            logger.error(message)
            exit(message)
        finally:
            if pidfile:
                pidfile.close()
    start.priority = 20

    def stop(self):
        logger.debug('"Mr. Sparkle, a joint venture of Matsumura Fishworks and Tamaribuchi Heavy Manufacturing Concern."')
        logger.info('Removing pidfile at %s  (PID: %s)"' % (self.PID_PATH, os.getpid() ) )

        # try to clean up the pid file, complain on fail
        try:
            os.remove(self.PID_PATH)
        except (OSError, IOError), fail:
            logger.error("Unable to remove %(path)s. [%(fail)s]" % {'path':self.PID_PATH, 'fail':str(fail)})

