#!/bin/bash

eval "$(/usr/sbin/ucr shell)"

set -x
set -e

. /usr/share/univention-lib/all.sh

ucs_parseCredentials "$@"

test -n "$binddn" || false
test -n "$bindpwdfile" || false

# get uid for binddn
uid="$(univention-ldapsearch -b "$binddn" -LLL uid | sed -n 's/^uid: //p')"
test_host="ucs-da-$$"

grafana_login () {
	local username="$1"
	local password="$2"
	local hostname="$3"

python - <<EOF
import requests
data = dict(user='$username', password='$password')
headers = {'Accept': 'application/json, text/plain, */*', 'Content-type': 'application/json;charset=UTF-8'}
r = requests.post('http://$hostname/ucs-dashboard/login', headers=headers, json=data)
r.raise_for_status()
EOF

}

prometheus_targets() {
	local password="$(cat /etc/machine.secret)"
	local username="$(hostname)\$"
	local url="https://$(hostname -f)/metrics-prometheus/api/v1/targets"
	python - <<EOF
import requests
r = requests.get('$url', auth=('$username', '$password'))
r.raise_for_status()
for i in r.json()['data']['activeTargets']:
	print(i.get('scrapeUrl'), i.get('lastError'))
	assert not i.get('lastError')
EOF
}

trap "{ 
	udm computers/domaincontroller_slave remove --dn "cn=$test_host,$ldap_base" || true
}" EXIT


# grafana
univention-dashboard-management
grafana_login "$(hostname)\$" "$(< /etc/machine.secret)" "$(hostname)"
grafana_login "$uid" "$(< $bindpwdfile)" "$(hostname)"

# prometheus
wget --http-user "$(hostname)\$" --http-password "$(< /etc/machine.secret)" -O - http://localhost/metrics-prometheus/ >/dev/null
wget --http-user "$uid" --http-password "$(< $bindpwdfile)" -O - http://localhost/metrics-prometheus/ >/dev/null

# check all prometheus targets are online
prometheus_targets

# prometheus listener, the hostname should be in this file
grep "$(hostname -f)" /var/lib/univention-appcenter/apps/prometheus/conf/targets.json
# add another host and check
udm computers/domaincontroller_slave create --binddn "$binddn" --bindpwdfile "$bindpwdfile" --ignore_exists --set name="$test_host" --append service=metrics-prometheus --set domain=$domainname
sleep 20
grep "$test_host.$domain" /var/lib/univention-appcenter/apps/prometheus/conf/targets.json
# and remove
udm computers/domaincontroller_slave remove --binddn "$binddn" --bindpwdfile "$bindpwdfile" --dn "cn=$test_host,$ldap_base"
sleep 20
! grep "$test_host.$domain" /var/lib/univention-appcenter/apps/prometheus/conf/targets.json


# node exporter
test -f /var/lib/prometheus/node-exporter/ucs-domain-info.prom
test -f /var/lib/prometheus/node-exporter/ucs-prometheus-info.prom
test -f /var/lib/prometheus/node-exporter/univention-server-metrics.prom

echo "success"

exit 0
