#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, ctypes, os, time, logging
from optparse import OptionParser
import daemon
from daemon.pidlockfile import PIDLockFile
import lockfile

import signal
from worker import ServiceWorker

def create_option_parser():
	parser = OptionParser()
	parser.add_option("-f", "--pidfile", dest="pidfile", type='string', action='store',
		          help="pidfile")
	parser.add_option("-d", action="store_true", dest="daemon", help="enable daemon mode")
	return parser

def create_daemon_context(pidfile):
	ctx = daemon.DaemonContext()
	ctx.pidfile = PIDLockFile(os.path.join('/tmp/', pidfile))
	ctx.detach_process = True
	ctx.umask = 0o022
	ctx.stdin = sys.stdin
	ctx.stdout = sys.stdout
	ctx.stderr = sys.stderr
	ctx.working_directory = os.path.dirname(os.path.abspath(__file__))

	ctx.signal_map = {
		signal.SIGTERM: exit,
		signal.SIGHUP: exit,
		signal.SIGTTOU: exit,
		signal.SIGTTIN: exit,
		signal.SIGTSTP: exit
	}

	return ctx

def main():
	parser = create_option_parser()
	(options, args) = parser.parse_args()

	if not options.pidfile:
		parser.error('pidfile not given')

	ctx = create_daemon_context(options.pidfile)

	if options.daemon:
		with ctx:
			with DaemonController() as dc:
				dc.run()
	else:
		with DaemonController() as dc:
			dc.run()


class DaemonController(object):
	def __enter__(self):
		return self

	def __exit__(self, exception_type, exception_val, trace):
		logging.debug('Exit')

	def __init__(self):
		logging.basicConfig(filename='logs/worker.log',level=logging.INFO)
		logging.debug("Deaemon init")
		self.worker = ServiceWorker()

	def run(self):
		logging.debug("Run")
		x = self.worker.work()
		time.sleep(0.01)
		logging.debug("Done")


if __name__ == '__main__':
	main()
