#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division, unicode_literals
##
##  This file is part of MoaT, the Master of all Things.
##
##  MoaT is Copyright © 2007-2015 by Matthias Urlichs <matthias@urlichs.de>,
##  it is licensed under the GPLv3. See the file `README.rst` for details,
##  including optimistic statements by the author.
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License (included; see the file LICENSE)
##  for more details.
##
##  This header is auto-generated and may self-destruct at any time,
##  courtesy of "make update". The original is in ‘scripts/_boilerplate.py’.
##  Thus, do not remove the next line, or insert any blank lines above.
##BP

import six
if six.PY2:
	import sys; sys.excepthook = None; del sys
from moat import patch;patch()
from moat.statement import main_words, global_words, Statement, \
	DoNothingHandler
from moat.module import Load,LoadDir,load_module
from moat.check import register_condition
from moat.context import Context
from moat.parser import parse
from moat.run import process_failure
from moat.twist import fix_exception
from moat.reactor import ShutdownHandler,mainloop,shut_down
from moat.logging import TRACE,DEBUG,INFO,WARN,ERROR,PANIC,\
	Logger, log_level
from signal import signal,SIGINT,SIGHUP,SIGQUIT
import sys
import os
import gevent

main_words.register_statement(Load)
main_words.register_statement(LoadDir)
main_words.register_statement(ShutdownHandler)
main_words.register_statement(DoNothingHandler)
load_module("ifelse")

from optparse import OptionParser
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-h","--help","-?", action="help",
	help="print this help text")
parser.add_option("-t", "--trace", dest="debuglevel", action="store",
	help="trace level (TRACE,DEBUG,INFO,WARN,ERROR,PANIC,NONE)", default="PANIC")
parser.add_option("-p", "--pidfile", dest="pidfile", action="store",
	help="file to write our PID to")

(opts, args) = parser.parse_args()
if not args:
	print("You need at least one config file!", file=sys.stderr)
	sys.exit(1)

class DoLogger(Logger):
	"""\
		This class implements one particular way to log things.
		"""
	def _slog(self,level,txt):
		if txt != ".":
			print(level+"> "+txt, file=self.out)

if opts.debuglevel != "NONE":
	for level in opts.debuglevel.split(","):
		if "=" in level:
			subsys,level = level.split("=")
			log_level(subsys, globals()[level])
		elif level == level.upper() and level in globals():
			DoLogger(level=globals()[level])
		else:
			raise KeyError("'%s' is not a debug level." % (level,))

if opts.pidfile:
	pid = open(opts.pidfile,"w")
	print(os.getpid(), file=pid)
	pid.close()

def _readcf():
	c = Context()
	try:
		for f in args:
			parse(f,ctx=c)
	except Exception as e:
		fix_exception(e)
		process_failure(e)
		shut_down()

reading = None
def readcf():
	global reading
	if reading:
		return
	reading = gevent.spawn(_readcf)
	def read_done(_):
		global reading
		reading = False
	reading.link(read_done)

signal(SIGINT, lambda a,b: gevent.spawn(shut_down))
signal(SIGQUIT,lambda a,b: gevent.spawn(shut_down))
signal(SIGHUP, lambda a,b: readcf())

mainloop(setup=readcf)

