#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Management Console Distribution Module
#
# Copyright 2008-2015 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/>.

import os
import sys

import univention.debug as ud
import univention.config_registry
import univention.management.console.modules.distribution.util as util

from optparse import OptionParser

configRegistry = univention.config_registry.ConfigRegistry()
configRegistry.load()

import inspect
def debugmsg( component, level, msg ):
	info = inspect.getframeinfo(inspect.currentframe().f_back)[0:3]
	printInfo = []
	if len(info[0])>28:
		printInfo.append('...'+info[0][-25:])
	else:
		printInfo.append(info[0])
	printInfo.extend(info[1:3])
	ud.debug(component, level, "%s:%s: %s" % (printInfo[0], printInfo[1], msg))
	print msg

def main():
	exitcode = 0
	debug_level = int( configRegistry.get('umc/module/debug/level','1') )
	if debug_level < 1:
		debug_level = 1
	if configRegistry.get('ucsschool/datadistribution/debug/level', None):
		debug_level = int( configRegistry.get('ucsschool/datadistribution/debug/level') )

	parser = OptionParser()
	parser.add_option( '-d', '--debug', action = 'store', type = 'int',
					   dest = 'debug', default = debug_level,
					   help = 'if set, debugging is activated and set to the specified level' )

#	parser.add_option( '-i', '--init', action = 'store_true',
#					   dest = 'init', default = False,
#					   help = 'init specified project' )

	parser.add_option( '-c', '--collect', action = 'store_true',
					   dest = 'collect', default = False,
					   help = 'collect specified project' )

	parser.add_option( '-s', '--distribute', action = 'store_true',
					   dest = 'distribute', default = False,
					   help = 'distribute specified project' )

#	parser.add_option( '-f', '--force', action = 'store_true',
#					   dest = 'force', default = False,
#					   help = 'force action' )

	parser.add_option( '-r', '--remove', action = 'store_true',
					   dest = 'remove', default = False,
					   help = 'remove project data' )

	( options, args ) = parser.parse_args()

	# open logging
	ud.init( '/var/log/univention/ucs-school-umc-distribution.log', 1, 1 )
	ud.set_level( ud.ADMIN, options.debug )
	debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution started: args=%s' % sys.argv)

	if int(options.collect) + int(options.distribute) + int(options.remove) != 1:
		debugmsg(ud.ADMIN, ud.ERROR, 'please specify one action: --distribute, --collect, or --remove')
		sys.exit(250)

	if len(args):
		if not os.path.exists( args[0] ):
			debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution: file does not exist: %s' % args[0])
			exitcode = 10
		elif not os.path.isfile( args[0] ):
			debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution: is not a file: %s' % args[0])
			exitcode = 20
		else:
			# try to load project data
			project = util.Project.load(args[0])
			if not project:
				# loading failed
				debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution finished: loading failed: %s' % (args[0]))
				exitcode = 30
			else:
				# project has been loaded
				if options.distribute:
					# distribute files
					usersFailed = []
					project.distribute(usersFailed)
					for iuser in usersFailed:
						debugmsg(ud.ADMIN, ud.ERROR, '  distribution to user failed: %s' % iuser)
					if usersFailed: exitcode = 40
					debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution finished: distributing: args=%s' % sys.argv)

				elif options.collect:
					# collect project files
					dirsFailed = []
					res = project.collect(dirsFailed)
					for idir in dirsFailed:
						debugmsg(ud.ADMIN, ud.ERROR, '  collecting from user failed: %s' % idir)
					if dirsFailed: exitcode = 50
					debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution finished: collecting: args=%s' % sys.argv)

				elif options.remove:
					# remove project data
					project.purge()
					debugmsg(ud.ADMIN, ud.ERROR, 'umc-distribution finished: removing: args=%s' % sys.argv)

	debugmsg(ud.ADMIN, ud.ERROR, 'finished umc-distribution: args=%s' % sys.argv)
	sys.exit(exitcode)

if __name__ == "__main__":
	main()

