#!/bin/bash

# do not configure app on update
test "x$1" = "xremove" && exit 0

eval "$(ucr shell)"

app_id="prometheus-alertmanager"

# update container for app settings
if [ "$1" = "settings" ]; then
    univention-app reinitialize "$app_id"
fi

# check if container is running
if ! docker ps --no-trunc | grep $(ucr get "appcenter/apps/$app_id/container"); then
	echo "Container is not running, exiting!"
	exit 0
fi

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

temp="$(mktemp)"
docker exec -u root $(ucr get appcenter/apps/$app_id/container) cat /etc/univention/base.conf > $temp
while read line; do
	export "$line"
done < <(ucr --shell dump; UNIVENTION_BASECONF=$temp ucr --shell dump; docker exec -u root $(ucr get appcenter/apps/$app_id/container) printenv)
rm -f $temp
export ldap_password="$(docker exec -u root $(ucr get "appcenter/apps/$app_id/container") cat /etc/machine.secret)"

# alertmanager config
custom_config="/var/lib/univention-appcenter/apps/$app_id/conf/custom-alertmanager.yml"

ucr filter << EOF > "/var/lib/univention-appcenter/apps/$app_id/conf/alertmanager.yml"
@!@
import yaml
base = 'prometheus-alertmanager/receivers/'
data = {}
for key, value in configRegistry.items():
	if not key.startswith(base):
		continue
	name = key[len(base):].split('/')[0]
	data[name] = value.split(',')

receivers = []
for name, emails in sorted(data.items()):
	email_configs = []
	for to_address in emails:
		email_configs.append({
			'send_resolved': configRegistry.is_true('prometheus-alertmanager/receiver-send-resolved', True),
			'to': to_address
		})
	receivers.append({
		'name': name,
		'email_configs': email_configs,
	})

receivers = receivers or [{'name': 'default', 'email_configs': [{'send_resolved': True, 'to': 'root@localhost'}]}]

config = {
	'global': {
		'smtp_smarthost': configRegistry.get('prometheus-alertmanager/smtp-host', 'localhost:25'),
		'smtp_from': configRegistry.get('prometheus-alertmanager/smtp-from', 'root@localhost'),
		'smtp_require_tls': configRegistry.is_true('prometheus-alertmanager/smtp-require-tls', False),
	},
	'templates': [
		'/etc/alertmanager/template/*.tmpl'
	],
	'route': {
		'group_by': ['alertname'],
		'group_wait': '30s',
		'group_interval': '5m',
		'repeat_interval': '1h',
		'receiver': receivers[0]['name'],
	},
	'receivers': receivers
}

if configRegistry.get('prometheus-alertmanager/smtp-auth-username'):
	config['global']['smtp_auth_username'] = configRegistry['prometheus-alertmanager/smtp-auth-username']
	try:
		with open(configRegistry.get('prometheus-alertmanager/smtp-auth-password-file', '/etc/prometheus_alertmanager_smtp.secret')) as fd:  # Auth method LOGIN and PLAIN
			config['global']['smtp_auth_password'] = fd.read()
	except OSError:
		pass
	if configRegistry.get('prometheus-alertmanager/smtp-auth-identity'):  # Auth method PLAIN
		config['global']['smtp_auth_identity'] = configRegistry['prometheus-alertmanager/smtp-auth-identity']
	if configRegistry.get('prometheus-alertmanager/smtp-auth-secret'):  # Auth method CRAM-MD5
		config['global']['smtp_auth_secret'] = configRegistry['prometheus-alertmanager/smtp-auth-secret']

print(yaml.dump(config, default_style=None, default_flow_style=False))
@!@
$(test -e $custom_config && cat $custom_config)
EOF
chmod 700 /var/lib/univention-appcenter/apps/$app_id/  # important! "nobody" must not reach the conf/ directory
chown 0:0 /var/lib/univention-appcenter/apps/$app_id/  # important! "nobody" must not reach the conf/ directory
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/"
univention-app stop "$app_id"
univention-app start "$app_id"

# alertmanager apache
touch /etc/prometheus_alertmanager_ldap.secret
chmod 600 /etc/prometheus_alertmanager_ldap.secret
echo -n "$ldap_password" > /etc/prometheus_alertmanager_ldap.secret
cat << EOF > /etc/apache2/ucs-sites.conf.d/prometheus-alertmanager.conf
LDAPTrustedMode TLS
<Location "/alertmanager/">
	AuthName "Alertmananger Access"
	AuthType Basic
	require valid-user
	<IfModule mod_authnz_ldap.c>
		AuthBasicProvider ldap
		AuthLDAPUrl "ldap://${ldap_server_name}:${ldap_server_port}/${ldap_base}?uid?sub?(objectClass=*)"
		AuthLDAPBindDN "${ldap_hostdn}"
		AuthLDAPBindPassword "exec:/bin/cat /etc/prometheus_alertmanager_ldap.secret"
	</IfModule>
	ProxyPass http://127.0.0.1:9093/ retry=0
	ProxyPassReverse http://127.0.0.1:9093/
</Location>
EOF
a2enmod ldap || true
a2enmod authnz_ldap || true
service apache2 reload

exit 0
