#!/usr/bin/python2.7
#
# Copyright 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/>.

from os import chmod, chown
from os.path import isdir, isfile, join
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

import univention.admin
import univention.admin.uldap
import univention.admin.config
import univention.admin.modules
import univention.config_registry

IGNORE_USERS = [
	'Administrator',
	'Guest',
	'krbtgt',
]

if __name__ == '__main__':
	parser = ArgumentParser(
		formatter_class=ArgumentDefaultsHelpFormatter,
		description='Place a .ucc-environment file into each users home directory (if not exist)',
	)
	parser.add_argument(
		'--ignore',
		metavar='USERNAME',
		type=str,
		nargs='*',
		default=IGNORE_USERS,
		help='Users to ignore'
	)
	parser.add_argument(
		'--force',
		action='store_true',
		help='Overwrite .ucc-environment if it exists'
	)
	args = parser.parse_args()
	
	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()
	
	univention.admin.modules.update()
	univention.admin.syntax.update_choices()
	lo, position = univention.admin.uldap.getAdminConnection()
	co = univention.admin.config.config()

	user_module = univention.admin.modules.get('users/user')
	users = univention.admin.modules.lookup(
		user_module,
		co,
		lo,
		scope='sub',
		superordinate=None,
		base=configRegistry.get('ldap_base'),
		filter=None
	)

	skiplist = (
		'/dev/null',
	)
	for user in users:
		if user.get('username') in args.ignore:
			continue
		unixHome = user.get('unixhome')
		if unixHome in skiplist or not isdir(unixHome):
			continue

		uccenv = join(unixHome, '.ucc-environment')
		if args.force or not isfile(uccenv):
			f = open(uccenv, 'w')
			f.write('KDEVARTMP DEFAULT="%s"\n' % join(unixHome, '.kde-cache'))
			f.close()
			chown(uccenv, int(user.get('uidNumber')), int(user.get('gidNumber')))
			chmod(uccenv, 0600)
