#!/bin/bash

. /usr/share/univention-docker-container-mode/lib.sh

ucr set repository/online/unmaintained=yes
univention-install --assume-yes python-pip || die "Setup failed"
pip install requests --pypi-url https://pypi.python.org/simple/ || die "Setup failed"
ucr set repository/online/unmaintained=no

/usr/share/univention-docker-container-mode/setup "$@" || die "Setup failed"

set -e
set -o pipefail

ucr set server/password/change=false

eval "$(ucr shell)"

LDAP_HOST="$ldap_server_name"
LDAP_PORT="$ldap_server_port"
LDAP_BASE="$ldap_base"
LDAP_USERNAME="$ldap_hostdn"
LDAP_PASSWORD="$(cat /etc/machine.secret)"

DOCKER_HOST="$(ucr get docker/host/name)"

APP_PREFIX="/openproject"

# Setup installer
INSTALLER_DAT="/etc/openproject/installer.dat"
cat > "$INSTALLER_DAT" <<CONFIG
mysql/autoinstall reuse
mysql/db_host ${DOCKER_HOST}
mysql/db_source_host ${HOSTNAME}
mysql/db_port 3306
mysql/db_username openproject
mysql/db_password $(cat /etc/mysql-openproject.secret)
mysql/db_name openproject
mysql/ssl no
server/autoinstall install
server/hostname localhost
server/ssl no
server/server_path_prefix ${APP_PREFIX}
smtp/autoinstall skip
memcached/autoinstall install
repositories/svn-install install
repositories/git-install install
repositories/svn-path /var/lib/univention-appcenter/openproject/data/openproject/svn
repositories/git-path /var/lib/univention-appcenter/openproject/data/openproject/git
repositories/git-http-backend /usr/lib/git-core/git-http-backend/
CONFIG

mkdir -p /var/lib/univention-appcenter/openproject/data/openproject/svn /var/lib/univention-appcenter/openproject/data/openproject/git /var/lib/univention-appcenter/openproject/data/openproject/files
chown openproject:openproject /var/lib/univention-appcenter/openproject/data/openproject/svn /var/lib/univention-appcenter/openproject/data/openproject/git /var/lib/univention-appcenter/openproject/data/openproject/files

openproject config:set LOCALE=en
openproject config:set EMAIL_DELIVERY_METHOD=sendmail
openproject config:set ATTACHMENTS_STORAGE_PATH="/var/lib/univention-appcenter/openproject/data/openproject/files"
openproject config:set OPENPROJECT_DISABLE__PASSWORD__LOGIN=false
openproject config:set OPENPROJECT_AUTHENTICATION_GLOBAL__BASIC__AUTH_USER="$(mkpasswd openproject | base64 | cut -c -12)"
openproject config:set OPENPROJECT_AUTHENTICATION_GLOBAL__BASIC__AUTH_PASSWORD="$(mkpasswd openproject | base64 | cut -c -12)"
openproject configure

openproject run rake setting:set[self_registration=3]
LDAP_URL="ldap://$LDAP_USERNAME:$LDAP_PASSWORD@$LDAP_HOST:$LDAP_PORT/$LDAP_BASE"
openproject run rake ldap:register url="$LDAP_URL" name=ucs_ldap onthefly=false map_login=uid map_firstname=givenName map_lastname=sn map_mail=mailPrimaryAddress


#SSO_FQDN="${ucs_server_sso_fqdn:-ucs-sso.$domainname}"
#IDP_CERT_FINGERPRINT=$(curl "https://$SSO_FQDN/simplesamlphp/saml2/idp/certificate" | openssl x509 -noout -fingerprint | cut -f2 -d '=')
#MAPPED_SAML_CONFIG="/opt/openproject/config/plugins/auth_saml/settings.yml"
#mkdir -p "$(dirname $MAPPED_SAML_CONFIG)"
#cat > "$MAPPED_SAML_CONFIG" <<EOF
#ucs:
#  name: "ucs"
#  display_name: "UCS"
#  # Use the default SAML icon
#  icon: "auth_provider-saml.png"
#  # omniauth-saml config
#  assertion_consumer_service_url: "https://$DOCKER_HOST/openproject/auth/ucs/callback"
#  issuer: "$APP"
#  idp_sso_target_url: "https://$SSO_FQDN/simplesamlphp/saml2/idp/SSOService.php"
#  idp_cert_fingerprint: "$IDP_CERT_FINGERPRINT"
#  attribute_statements:
#    email: ['mailPrimaryAddress']
#    name: ['gecos']
#    first_name: ['givenName']
#    last_name: ['sn']
#    admin: ['openproject-isadmin']
#EOF

service openproject restart

# FIXME! Copied from update_app_version_custom
# Listener
tmp_listener_file="/tmp/openproject-listener.py"

cat > "$tmp_listener_file" << EOF
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# OpenProject integration
#  Listener module for syncing UCS users to OpenProject
#
# 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/>.

__package__ = '' 	# workaround for PEP 366


import sqlite3
import os
import os.path
from json import dumps, loads
import subprocess
from datetime import datetime
from contextlib import contextmanager

from requests import request

import listener
import univention.debug as ud
from univention.config_registry import ConfigRegistry


name = 'openproject'
description = 'Sync users to OpenProject'
filter = '(univentionObjectType=users/user)'
attributes = ['uid', 'givenName', 'sn', 'openprojectActivated', 'openproject-isadmin', 'mailPrimaryAddress', 'disabled']
modrdn = '1'


class Task(object):
	def __init__(self, uuid, dn, new, old, command, status, open, created):
		self.uuid = uuid
		self.dn = dn
		self.new = new
		self.old = old
		self.command = command
		self.status = status
		self.open = open
		self.created = created

	def __str__(self):
		return '%s (%s %s @ %s)' % (self.dn, self.command, self.uuid, self.created)


class OperationFailed(Exception):
	def __init__(self, msg='FAIL', retry=False):
		self.status = msg
		self.retry = retry

	def __str__(self):
		return '%s (retry: %r)' % (self.status, self.retry)


class UniventionListenerObject(object):
	def __init__(self, attrs):
		for key, value in attrs.iteritems():
			setattr(self, key, value)

	def __eq__(self, other):
		return self.__dict__ == other.__dict__

	def __repr__(self):
		return repr(self.__dict__)


class UniventionListenerHandler(object):
	ldap_object_class = UniventionListenerObject
	root_privileges = False

	def __init__(self, name, attrs, multi_values=None):
		self.name = name
		self.attrs = attrs
		self.multi_values = multi_values or []
		self.initialize_db()

	def initialize_db(self):
		with self.root_uid_if_requested():
			db_file = self.get_db_file()
			create_db = not os.path.exists(db_file)
			self.log('Using %s for database. New? %r' % (db_file, create_db))
			self.conn = sqlite3.connect(db_file)
			self.cursor = self.conn.cursor()
			if create_db:
				os.chmod(db_file, 0600)
				self.create_db()

	def get_db_file(self):
		return '/var/lib/univention-appcenter/apps/%s/data/listener.db' % self.name

	def create_db(self):
		self.cursor.execute('CREATE TABLE tasks (uuid TEXT, dn TEXT, new TEXT, old TEXT, command TEXT, status TEXT, open INTEGER, created TEXT)')
		self.conn.commit()

	def make_obj_from_ldap_attrs(self, attrs):
		obj_attrs = {'uuid': attrs.get('entryUUID', [None])[0]}
		for attr in self.attrs:
			value = attrs.get(attr)
			if value is not None and attr not in self.multi_values:
				value = value[0]
			obj_attrs[attr] = value
		return self.ldap_object_class(obj_attrs)

	def make_obj_from_db_string(self, db_str):
		attrs = loads(db_str)
		return self.ldap_object_class(attrs)

	def log(self, msg, level=ud.PROCESS):
		msg = '%s: %s' % (self.name, msg)
		ud.debug(ud.LISTENER, level, msg)

	def handle(self, dn, new, old, command):
		with self.root_uid_if_requested():
			for attr_dict in [new, old]:
				if attr_dict:
					for key, value in attr_dict.items():
						attr_dict[key] = [val.decode('latin1') for val in value]
			new, old = self.make_obj_from_ldap_attrs(new), self.make_obj_from_ldap_attrs(old)
			uuid = new.uuid or old.uuid
			task = Task(uuid, dn, new, old, command, 'NEW', True, None)
			self.save_task(task)
			for task in self.get_open_tasks():
				if self.handle_task(task):
					continue
				else:
					break

	@contextmanager
	def root_uid_if_requested(self):
		try:
			if self.root_privileges:
				listener.setuid(0)
			yield
		finally:
			if self.root_privileges:
				listener.unsetuid()

	def handle_task(self, task):
		try:
			if task.command == 'a' or task.command == 'n' and task.dn != 'cn=Subschema':
				self.log('Add %s' % task.dn)
				task.status = self.on_create(task.dn, task.new)
			elif task.command == 'd':
				self.log('Delete %s' % task.dn)
				task.status = self.on_delete(task.dn, task.old)
			elif task.command == 'r':
				self.log('Rename / move %s. Next "Add" will probably be this object' % task.dn)
				raise OperationFailed('HOLD', retry=True)
			elif task.command == 'm':
				self.log('Modify %s' % task.dn)
				task.status = self.on_modify(task.dn, task.new, task.old)
		except OperationFailed as exc:
			self.log('%s: %s' % (task, exc), ud.INFO)
			task.status = exc.status
			task.open = exc.retry
		else:
			self.log('%s: OK' % task, ud.INFO)
			if task.status is None:
				task.status = 'OK'
			task.open = False
		finally:
			if task.open:
				self.save_task(task)
			else:
				self.delete_task(task) or self.save_task(task)
		return not task.open

	def save_task(self, task):
		old_tasks = self.get_tasks_from_query('WHERE uuid = ? AND open = 1', task.uuid)
		if old_tasks:
			self.log('Update %s' % task.uuid)
			if len(old_tasks) > 1:
				self.log('%d open tasks for UUID %s found! This may cause problems. Deleting those' % (len(old_tasks), task.uuid))
				for obsolete_task in old_tasks[1:]:
					self.delete_task(obsolete_task)
			old_task = old_tasks[0]
			self.merge_task(task, old_task)
			self.cursor.execute('UPDATE tasks SET dn = ?, new = ?, old = ?, command = ?, status = ?, open = ? WHERE uuid = ? AND open = 1', (task.dn, dumps(task.new.__dict__), dumps(task.old.__dict__), task.command, task.status, task.open, task.uuid))
		else:
			task.created = str(datetime.now())
			self.log('Create %s' % task)
			self.cursor.execute('INSERT INTO tasks (uuid, dn, new, old, command, status, open, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', (task.uuid, task.dn, dumps(task.new.__dict__), dumps(task.old.__dict__), task.command, task.status, task.open, task.created))
		if task.command != 'r':
			for task in self.get_tasks_from_query('WHERE command = "r" AND open = 1'):
				task.command = 'd'
				self.save_task(task)
		self.conn.commit()
		return True

	def delete_task(self, task):
		self.log('Delete %s' % task)
		if task.uuid and task.created:
			self.cursor.execute('DELETE FROM tasks WHERE uuid = ? AND created = ?', (task.uuid, task.created))
			self.conn.commit()
			return True

	def merge_task(self, new_task, old_task):
		self.log('Merge %s and %s' % (new_task, old_task))
		if new_task.uuid == old_task.uuid and new_task.created != old_task.created:
			if new_task.command in ['d', 'r']:
				if old_task.command == 'a' and self.delete_task(old_task):
					return False
			elif new_task.command == 'a' and old_task.command == 'r':
				new_task.command = 'm'
				new_task.old = old_task.old
			elif old_task.command == 'a':
				if new_task.command == 'r' and self.delete_task(old_task):
					return False
				new_task.command = 'a'
				new_task.old = self.make_obj_from_ldap_attrs({})
			elif new_task.command == 'm' and old_task.command == 'm':
				new_task.old = old_task.old
			elif new_task.command == 'n':
				pass
			else:
				raise NotImplementedError('Found old task: %r. Cannot merge with new task %r' % (old_task, new_task))
		else:
			self.log('... unable to merge. Either the same or completely different')

	def task_from_db_row(self, row):
		task = Task(*row)
		task.new = self.make_obj_from_db_string(task.new)
		task.old = self.make_obj_from_db_string(task.old)
		return task

	def get_tasks_from_query(self, query, *args):
		tasks = []
		for row in self.cursor.execute('SELECT uuid, dn, new, old, command, status, open, created FROM tasks %s' % query, args):
			task = self.task_from_db_row(row)
			tasks.append(task)
		return tasks

	def get_open_tasks(self):
		return self.get_tasks_from_query('WHERE open = 1 ORDER BY created')

	def on_create(self, dn, obj):
		pass

	def on_delete(self, dn, obj):
		pass

	def on_modify(self, dn, new_obj, old_obj):
		pass


ucr = ConfigRegistry()
ucr.load()


class OpenProjectListener(UniventionListenerHandler):
	root_privileges = True
	base_url = 'http://localhost:6000/openproject/api/v3'

	def __init__(self, name, attrs, multi_values=None):
		super(OpenProjectListener, self).__init__(name, attrs, multi_values)
		self._op_user = None
		self._op_pass = None

	def _get_op_cred(self):
		if self._op_user is None:
			try:
				output = subprocess.check_output(['openproject', 'run', 'env'])
			except subprocess.CalledProcessError:
				raise OperationFailed('DOWN', True)
			else:
				env = dict(line.split('=', 1) for line in output.splitlines() if line)
				self._op_user = env['OPENPROJECT_AUTHENTICATION_GLOBAL__BASIC__AUTH_USER']
				self._op_pass = env['OPENPROJECT_AUTHENTICATION_GLOBAL__BASIC__AUTH_PASSWORD']
				self.log('Got credentials for API')
		return self._op_user, self._op_pass

	def _openproject_attrs(self, obj):
		ret = {}
		ret['login'] = obj.uid
		ret['email'] = obj.mailPrimaryAddress
		ret['firstName'] = obj.givenName or obj.sn
		ret['lastName'] = obj.sn
		ret['admin'] = getattr(obj, 'openproject-isadmin') == 'TRUE'
		#ret['password'] = 'halloHALLO1!'
		#ret['auth_source'] = 'ucs_ldap'
		ret['_links'] = {'authSource': {'href': 'http://localhost:6000/api/v3/auth_sources/ucs_ldap'}}
		#ret['status'] = 'active'
		ret['language'] = 'en'
		return ret

	def _openproject_user_id(self, obj):
		users = self.request('GET', '/users')['elements']
		for user in users:
			if user['login'] == obj.uid:
				return user['id']

	def on_create(self, dn, obj):
		if obj.mailPrimaryAddress and obj.openprojectActivated:
			user = self.request('POST', '/users', self._openproject_attrs(obj))
			if obj.disabled:
				self.request('POST', '/users/%s/lock' % user['id'])

	def on_delete(self, dn, obj):
		user_id = self._openproject_user_id(obj)
		if user_id:
			self.request('DELETE', '/users/%s' % user_id)

	def on_modify(self, dn, new_obj, old_obj):
		user_id = self._openproject_user_id(new_obj)
		if user_id:
			if new_obj.mailPrimaryAddress:
				self.request('PATCH', '/users/%s' % user_id, self._openproject_attrs(new_obj))
			if new_obj.disabled or not new_obj.openprojectActivated:
				self.request('POST', '/users/%s/lock' % user_id)
			else:
				self.request('DELETE', '/users/%s/lock' % user_id)
		else:
			self.on_create(dn, new_obj)

	def request(self, command, uri, data=None):
		self.log('%s to %s - %r' % (command, uri, data))
		response = request(command, self.base_url + uri, json=data, auth=self._get_op_cred())
		try:
			answer = response.json()
		except (ValueError, TypeError):
			raise OperationFailed('ERR', retry=True)
		if answer['_type'] == 'Collection':
			return answer['_embedded']
		elif answer['_type'] == 'Error':
			self.log(answer['message'], ud.ERROR)
			raise OperationFailed('ERR', retry=True)


listener_object = OpenProjectListener(name, attributes)


def handler(dn, new, old, command):
	listener_object.handle(dn, new, old, command)
EOF

listener_file="/usr/lib/univention-directory-listener/system/openproject.py"
if [ ! -e "$listener_file" -o ! "$(diff -q "$tmp_listener_file" "$listener_file")" ]; then
  cp "$tmp_listener_file" "$listener_file"
  service univention-directory-listener restart
fi
