#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Management Console
#  handles UMC requests for a specified UMC module
#
# Copyright 2006-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.management.console.log import MODULE, log_init
from univention.management.console.config import MODULE_DEBUG_LEVEL, ucr
from univention.lib.i18n import Locale, Translation

from daemon.daemon import DaemonContext
from optparse import OptionParser

import locale
import os
import os.path
import sys

import notifier
import notifier.log as nflog

if __name__ == '__main__':
	if os.getuid() != 0:
		sys.stderr.write( '%s must be started as root\n' % os.path.basename( sys.argv[ 0 ] ) )
		sys.exit( 1 )

	parser = OptionParser( usage = "usage: %prog [options]" )
	parser.add_option( '-s', '--socket', type = 'string', action = 'store', dest = 'socket',
					   help = 'defines the socket to bind to' )
	parser.add_option( '-l', '--language', type = 'string', action = 'store', dest = 'language', default = 'C',
					   help = 'defines the language to use' )
	parser.add_option( '-m', '--module', type = 'string', action = 'store', dest = 'module',
					   help = 'set the UMC daemon module to load' )
	parser.add_option( '-n', '--notifier', type = 'string', action = 'store', dest = 'notifier', default = 'generic',
					   help = 'defines the notifier implementation to use' )

	default_debug = MODULE_DEBUG_LEVEL
	parser.add_option( '-d', '--debug', action = 'store', type = 'int', dest = 'debug', default = default_debug,
					   help = 'if given then debugging is activated and set to the specified level [default: %default]' )
	parser.add_option( '-L', '--log-file', action = 'store',  dest = 'logfile', default = 'management-console-module', help = 'specifies an alternative log file [default: %default-<module name>.log]' )

	( options, arguments ) = parser.parse_args()

	daemon = DaemonContext( detach_process = False, umask = 0077 )
	daemon.open()

	# MUST be called after initializing the deamon
	if options.notifier.lower() == 'generic':
		notifier.init( notifier.GENERIC )
	elif options.notifier.lower() == 'qt':
		import PyQt4.Qt as qt
		qApp = qt.QCoreApplication( sys.argv )
		notifier.init( notifier.QT )

	# init logging
	debug_fd = log_init( '%s-%s' % ( options.logfile, options.module ), options.debug )
	# no notifier logging
	nflog.instance.handlers = []
	# to activate notifier logging
	# nflog.set_level( nflog.DEBUG )
	# nflog.open()

	localeok = False
	try:
		locale_obj = Locale( options.language )
		locale.setlocale( locale.LC_MESSAGES, str( locale_obj ) )
		localeok = True
		translation = Translation('univention-management-console')
		translation.set_language(options.language)
	except:
		MODULE.error( 'The specified locale is not available (cmdline: %s)' % str( locale_obj ) )

	import univention.management.console.protocol as umcp

	if not options.socket:
		raise SystemError( 'socket name is missing' )

	# make sure the directory where to place socket files exists
	if not os.path.exists('/var/run/univention-management-console'):
		os.mkdir('/var/run/univention-management-console')

	# get the timeout
	session_timeout = 300
	try:
		session_timeout = int( ucr.get( 'umc/module/timeout', 300 ) )
	except TypeError, ValueError:
		MODULE.warn( 'Failed to read module timeout from UCR variable umc/module/timeout. Using default of 300 seconds' )

	try:
		module = umcp.ModuleServer( options.socket, options.module, check_acls = False, timeout = session_timeout )

		notifier.loop()
	except (SystemExit, KeyboardInterrupt):
		raise
	except:
		import traceback
		MODULE.error(traceback.format_exc())
		raise
