#!/bin/bash

app_id="prometheus"

# make prometheus port available on localhost only
ucr set appcenter/apps/$app_id/docker/params='-p 127.0.0.1:9090:9090'

# settings default
ucr set \
	prometheus/storage/tsdb/retention?15d \
	prometheus/query/lookback-delta?12h

mkdir -p /var/lib/univention-appcenter/apps/$app_id/data/
mkdir -p /var/lib/univention-appcenter/apps/$app_id/conf/

# default config
touch /var/lib/univention-appcenter/apps/$app_id/conf/prometheus.yml
if [ ! -e /var/lib/univention-appcenter/apps/$app_id/conf/targets.json ]; then
cat << EOF > /var/lib/univention-appcenter/apps/$app_id/conf/targets.json
[
  {
    "targets": [ ]
  }
]
EOF
fi
if [ ! -e "/var/lib/univention-appcenter/apps/$app_id/conf/alertmanager-targets.json" ]; then
cat << EOF > "/var/lib/univention-appcenter/apps/$app_id/conf/alertmanager-targets.json"
[
  {
    "targets": [ ]
  }
]
EOF
fi

chmod -R 750 /var/lib/univention-appcenter/apps/$app_id/conf/
chown -R 65534:0 /var/lib/univention-appcenter/apps/$app_id/conf/ # nobody user in container
chmod -R 750 /var/lib/univention-appcenter/apps/$app_id/data/
chown -R 65534:0 /var/lib/univention-appcenter/apps/$app_id/data/

# prometheus target listener
cat << "EOF" > /usr/lib/univention-directory-listener/system/prometheus-targets.py
# -*- coding: utf-8 -*-
#
# Univention Directory Listener
#
# Copyright 2004-2018 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 __future__ import absolute_import

import listener

import ldap
import json

import univention.debug as ud
import univention.uldap

name = 'prometheus-targets'
description = 'Update prometheus target list'
filter = '(|(univentionService=metrics-prometheus)(univentionService=metrics-node))'
target_file = '/var/lib/univention-appcenter/apps/prometheus/conf/targets.json'
attributes = []


def handler(dn, new, old):
	update_targets()


def update_targets():
	targets = []
	lo = None

	# get targets
	listener.setuid(0)
	try:
		lo = univention.uldap.getMachineConnection(ldap_master=False)
	except ldap.SERVER_DOWN:
		lo = univention.uldap.getMachineConnection()
	finally:
		listener.unsetuid()

	if lo:
		for dn, attr in lo.search(filter):
			if 'cn' in attr and 'associatedDomain' in attr:
				ud.debug(ud.LISTENER, ud.PROCESS, '{0}: found dn {1}'.format(name, dn))
				fqdn = b'%s.%s' % (attr['cn'][0], attr['associatedDomain'][0])
				for service in attr.get('univentionService', []):
					if service.startswith(b'metrics-'):
						targets.append(service.decode('UTF-8') + '.' + fqdn.decode('UTF-8'))
	ud.debug(ud.LISTENER, ud.PROCESS, '{0}: found targets {1}'.format(name, targets))

	# write prometheus json file
	listener.setuid(0)
	try:
		with open(target_file) as f:
			data = json.load(f)
		data[0]['targets'] = targets
		with open(target_file, 'w') as f:
			json.dump(data, f)
	finally:
		listener.unsetuid()


def postrun():
	ud.debug(ud.LISTENER, ud.PROCESS, '{0}: updating target list in postrun'.format(name))
EOF

# alertmanager target listener
cat << "EOF" > /usr/lib/univention-directory-listener/system/alertmanager-targets.py
# -*- coding: utf-8 -*-
#
# Univention Directory Listener
#
# Copyright 2022 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 __future__ import absolute_import

import listener

import ldap
import json

import univention.debug as ud
import univention.uldap

name = 'alertmanager-targets'
description = 'Update alertmanager target list'
filter = '(univentionService=alertmanager)'
target_file = '/var/lib/univention-appcenter/apps/prometheus/conf/alertmanager-targets.json'
attributes = []


def handler(dn, new, old):
	update_targets()


def update_targets():
	targets = []
	lo = None

	# get targets
	listener.setuid(0)
	try:
		lo = univention.uldap.getMachineConnection(ldap_master=False)
	except ldap.SERVER_DOWN:
		lo = univention.uldap.getMachineConnection()
	finally:
		listener.unsetuid()

	if lo:
		for dn, attr in lo.search(filter):
			if 'cn' in attr and 'associatedDomain' in attr:
				ud.debug(ud.LISTENER, ud.PROCESS, '{0}: found dn {1}'.format(name, dn))
				fqdn = b'%s.%s' % (attr['cn'][0], attr['associatedDomain'][0])
				if b'alertmanager' in attr.get('univentionService', []):
					targets.append('alertmanager.%s' % (fqdn.decode('UTF-8'),))
	ud.debug(ud.LISTENER, ud.PROCESS, '{0}: found targets {1}'.format(name, targets))

	# write alertmanager json file
	listener.setuid(0)
	try:
		with open(target_file) as f:
			data = json.load(f)
		data[0]['targets'] = targets
		with open(target_file, 'w') as f:
			json.dump(data, f)
	finally:
		listener.unsetuid()
EOF

# prometheus ucs metrics
cat << "EOF" > /usr/sbin/univention-metrics-prometheus
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2018 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 subprocess

EXPORTER_DIR = '/var/lib/prometheus/node-exporter'
DATA_DIR = '/var/lib/univention-appcenter/apps/prometheus/data/data'

if __name__ == '__main__':
	data = []

	try:
		out = subprocess.check_output(['du', '-xsb0', DATA_DIR])
		size = out.decode('UTF-8').split()[0]
	except (OSError, subprocess.CalledProcessError):
		size = '0'
	data.append('prometheus_data_directory_size_bytes{directory="%s"} %s' % (DATA_DIR, size))

	tmp_filename = os.path.join(EXPORTER_DIR, 'ucs-prometheus-info.%s' % os.getpid())
	filename = os.path.join(EXPORTER_DIR, 'ucs-prometheus-info.prom')
	with open(tmp_filename, 'w') as fd:
		for d in data:
			fd.write(d + '\n')
	if os.path.exists(tmp_filename):
		os.rename(tmp_filename, filename)
EOF
chmod 755 /usr/sbin/univention-metrics-prometheus

# cron job
cat << "EOF" > /etc/cron.d/univention-metrics-prometheus
PATH=/sbin:/bin:/usr/sbin:/usr/bin
*/10 * * * * root /usr/sbin/univention-metrics-prometheus
EOF

if python3 -c 'import argparse; p = argparse.ArgumentParser(); p.add_argument("--version"); p.add_argument("--old-version"); a = p.parse_known_args()[0]; exit(not (a.version == "2.35.0-4" and a.old_version in ("2.35.0-2", "2.35.0-3")))' "$@"; then
	sed -i 's#ca_file: .*#ca_file: /etc/ssl/certs/ca-certificates.crt#g' /var/lib/univention-appcenter/apps/prometheus/conf/prometheus.yml
	univention-app restart 4.4/prometheus=2.35.0-4
	echo $?
fi

exit 0
