#!/bin/bash


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

eval "$(ucr shell)"

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

app_id=admin-dashboard

# 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

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)"
export admin_group="$(custom_groupname Domain\ Admins)"
# cat - | envsubst

# settings can be empty
test -z "$prometheus_server" && export prometheus_server="$docker_host_name"
test -z "$ldap_ssl_skip_verify" && export ldap_ssl_skip_verify=false
test -z "$datasource_tls_skip_verify" && datasource_tls_skip_verify=false

# grafana ini
cat << EOF > /var/lib/univention-appcenter/apps/$app_id/conf/grafana/grafana.ini
[server]
root_url = %(protocol)s://%(domain)s/ucs-dashboard/

[auth]
login_cookie_name = grafana8_session

[auth.ldap]
enabled = true
config_file = /var/lib/univention-appcenter/apps/admin-dashboard/conf/grafana/ldap.toml
allow_sign_up = true
EOF

# custom ini
if [ -e "/var/lib/univention-appcenter/apps/$app_id/conf/grafana/custom.ini" ]; then
    cat "/var/lib/univention-appcenter/apps/$app_id/conf/grafana/custom.ini" >> "/var/lib/univention-appcenter/apps/$app_id/conf/grafana/grafana.ini"
fi

# grafana ldap.toml
custom_ldap_config="/var/lib/univention-appcenter/apps/admin-dashboard/conf/grafana/custom-ldap.toml"
cat << EOF > /var/lib/univention-appcenter/apps/$app_id/conf/grafana/ldap.toml
# To troubleshoot and get more log info enable ldap debug logging in grafana.ini
# [log]
# filters = ldap:debug

[[servers]]
# Ldap server host (specify multiple hosts space separated)
host = "${ldap_server_name}"
# Default port is 389 or 636 if use_ssl = true
port = ${ldap_server_port}
# Set to true if ldap server supports TLS
use_ssl = false
# Set to true if connect ldap server with STARTTLS pattern (create connection in insecure, then upgrade to secure connection with TLS)
start_tls = true
# set to true if you want to skip ssl cert validation
ssl_skip_verify = ${ldap_ssl_skip_verify}
# set to the path to your root CA certificate or leave unset to use system defaults
# root_ca_cert = "/path/to/certificate.crt"

# Search user bind dn
bind_dn = "${ldap_hostdn}"
# Search user bind password
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
bind_password = "${ldap_password}"

# User search filter, for example "(cn=%s)" or "(sAMAccountName=%s)" or "(uid=%s)"
search_filter = "(uid=%s)"

# An array of base dns to search through
search_base_dns = ["${ldap_base}"]

# In POSIX LDAP schemas, without memberOf attribute a secondary query must be made for groups.
# This is done by enabling group_search_filter below. You must also set member_of= "cn"
# in [servers.attributes] below.

# Users with nested/recursive group membership and an LDAP server that supports LDAP_MATCHING_RULE_IN_CHAIN
# can set group_search_filter, group_search_filter_user_attribute, group_search_base_dns and member_of
# below in such a way that the user's recursive group membership is considered.
#
# Nested Groups + Active Directory (AD) Example:
#
#   AD groups store the Distinguished Names (DNs) of members, so your filter must
#   recursively search your groups for the authenticating user's DN. For example:
#
#     group_search_filter = "(member:1.2.840.113556.1.4.1941:=%s)"
#     group_search_filter_user_attribute = "distinguishedName"
#     group_search_base_dns = ["ou=groups,dc=grafana,dc=org"]
#
#     [servers.attributes]
#     ...
#     member_of = "distinguishedName"

## Group search filter, to retrieve the groups of which the user is a member (only set if memberOf attribute is not available)
group_search_filter = "(&(objectClass=posixGroup)(memberUid=%s))"
## Group search filter user attribute defines what user attribute gets substituted for %s in group_search_filter.
## Defaults to the value of username in [server.attributes]
## Valid options are any of your values in [servers.attributes]
## If you are using nested groups you probably want to set this and member_of in
## [servers.attributes] to "distinguishedName"
group_search_filter_user_attribute = "uid"
## An array of the base DNs to search through for groups. Typically uses ou=groups
group_search_base_dns = ["${ldap_base}"]

# Specify names of the ldap attributes your ldap uses
[servers.attributes]
name = "givenName"
surname = "sn"
username = "uid"
member_of = "cn"
email =  "mailPrimaryAddress"

# Map ldap groups to grafana org roles
[[servers.group_mappings]]
group_dn = "${admin_group}"
org_role = "Admin"
# The Grafana organization database id, optional, if left out the default org (id 1) will be used
# org_id = 1

[[servers.group_mappings]]
group_dn = "DC Backup Hosts"
org_role = "Admin"

[[servers.group_mappings]]
group_dn = "DC Slave Hosts"
org_role = "Admin"

#[[servers.group_mappings]]
#group_dn = "cn=users,dc=grafana,dc=org"
#org_role = "Editor"
#
#[[servers.group_mappings]]
## If you want to match all (or no ldap groups) then you can use wildcard
#group_dn = "*"
#org_role = "Viewer"

$(test -e $custom_ldap_config && cat $custom_ldap_config)
EOF

# datasources provisioning
cat << EOF > /var/lib/univention-appcenter/apps/$app_id/data/provisioning/datasources/univention.yaml
# config file version
apiVersion: 1

# list of datasources to insert/update depending
# what's available in the database
datasources:
  # <string, required> name of the datasource. Required
- name: Univention
  # <string, required> datasource type. Required
  type: prometheus
  # <string, required> access mode. proxy or direct (Server or Browser in the UI). Required
  access: proxy
  # <int> org id. will default to orgId 1 if not specified
  orgId: 1
  # <string> url
  url: https://${prometheus_server}/metrics-prometheus/
  # <string> Deprecated, use secureJsonData.password
  password:
  # <string> database user, if used
  user:
  # <string> database name, if used
  database:
  # <bool> enable/disable basic auth
  basicAuth: true
  # <string> basic auth username
  basicAuthUser: ${HOSTNAME}\$
  # <bool> enable/disable with credentials headers
  withCredentials:
  # <bool> mark as default datasource. Max one per org
  isDefault: true
  # <map> fields that will be converted to json and stored in json_data
  jsonData:
    tlsSkipVerify: ${datasource_tls_skip_verify}
  # <string> json object of data that will be encrypted
  secureJsonData:
    # <string> basic auth password
    basicAuthPassword: ${ldap_password}
  version: 1
  # <bool> allow users to edit datasources from the UI.
  editable: false
EOF

# dashboard provisioning
cat << "EOF" > /var/lib/univention-appcenter/apps/$app_id/data/provisioning/dashboards/univention.yaml
apiVersion: 1

providers:
- name: 'univention'
  orgId: 1
  folder: ''
  type: file
  disableDeletion: true
  updateIntervalSeconds: 30 # how often Grafana will scan for changed dashboards
  options:
    path: /var/lib/univention-appcenter/apps/admin-dashboard/data/provisioning/dashboards/
EOF

# dashboard provisioning
cat << "EOF" > /var/lib/univention-appcenter/apps/$app_id/data/provisioning/dashboards/home-dashboard.json
{
  "id": null,
  "uid": "univention-home-dashboard",
  "folderId": 0,
  "title": "Domain Dashboard",
  "tags": [
    "templated"
  ],
  "style": "light",
  "timezone": "browser",
  "editable": false,
  "hideControls": false,
  "overwrite": true,
  "graphTooltip": 1,
  "templating": {
    "list": [
      {
        "allValue": null,
        "current": {
          "isNone": true,
          "text": "None",
          "value": ""
        },
        "datasource": "Univention",
        "hide": 2,
        "includeAll": false,
        "label": null,
        "multi": false,
        "name": "instances",
        "options": [],
        "query": "label_values(instance)",
        "refresh": 2,
        "regex": "",
        "sort": 0,
        "tagValuesQuery": "",
        "tags": [],
        "tagsQuery": "",
        "type": "query",
        "useTags": false
      },
      {
        "allValue": null,
        "current": {
          "isNone": true,
          "text": "None",
          "value": ""
        },
        "datasource": "Univention",
        "hide": 2,
        "includeAll": false,
        "label": null,
        "multi": false,
        "name": "ldap_master",
        "options": [],
        "query": "query_result(ucs_domain_info)",
        "refresh": 2,
        "regex": ".*ldap_master=\\\"([^\\\"]+)\\\".*",
        "sort": 0,
        "tagValuesQuery": "",
        "tags": [],
        "tagsQuery": "",
        "type": "query",
        "useTags": false
      }
    ]
  },
  "time": {
    "from": "now-12h",
    "to": "now"
  },
  "timepicker": {
    "to": "now-5m",
    "time_options": [],
    "refresh_intervals": []
  },
  "annotations": {
    "list": []
  },
  "refresh": "5s",
  "schemaVersion": 16,
  "version": 0,
  "links": [],
  "panels": [
    {
      "cacheTimeout": null,
      "colorBackground": false,
      "colorValue": false,
      "colors": [
        "#299c46",
        "rgba(237, 129, 40, 0.89)",
        "#d44a3a"
      ],
      "datasource": "Univention",
      "format": "none",
      "gauge": {
        "maxValue": 100,
        "minValue": 0,
        "show": false,
        "thresholdLabels": false,
        "thresholdMarkers": true
      },
      "gridPos": {
        "h": 2,
        "w": 3,
        "x": 7,
        "y": 5
      },
      "id": 10,
      "interval": null,
      "links": [
        {
          "targetBlank": true,
          "title": "Linux to Clients",
          "type": "absolute",
          "url": "https://${ldap_master}/univention/management/#module=udm:computers/computer:0:"
        }
      ],
      "mappingType": 1,
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "maxDataPoints": 100,
      "nullPointMode": "connected",
      "nullText": null,
      "postfix": "",
      "postfixFontSize": "50%",
      "prefix": "",
      "prefixFontSize": "50%",
      "rangeMaps": [
        {
          "from": "null",
          "text": "N/A",
          "to": "null"
        }
      ],
      "sparkline": {
        "fillColor": "rgba(31, 118, 189, 0.18)",
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "show": false
      },
      "tableColumn": "",
      "targets": [
        {
          "expr": "ucs_client_count",
          "format": "time_series",
          "intervalFactor": 1,
          "refId": "A"
        }
      ],
      "thresholds": "",
      "title": "Domain Clients",
      "type": "singlestat",
      "valueFontSize": "80%",
      "valueMaps": [
        {
          "op": "=",
          "text": "N/A",
          "value": "null"
        }
      ],
      "valueName": "current"
    },
    {
      "cacheTimeout": null,
      "colorBackground": false,
      "colorValue": false,
      "colors": [
        "#299c46",
        "rgba(237, 129, 40, 0.89)",
        "#d44a3a"
      ],
      "datasource": "Univention",
      "format": "none",
      "gauge": {
        "maxValue": 100,
        "minValue": 0,
        "show": false,
        "thresholdLabels": false,
        "thresholdMarkers": true
      },
      "gridPos": {
        "h": 2,
        "w": 3,
        "x": 7,
        "y": 3
      },
      "id": 8,
      "interval": null,
      "links": [
        {
          "targetBlank": true,
          "title": "Link to Servers",
          "type": "absolute",
          "url": "https://${ldap_master}/univention/management/#module=udm:computers/computer:0:"
        }
      ],
      "mappingType": 1,
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "maxDataPoints": 100,
      "nullPointMode": "connected",
      "nullText": null,
      "postfix": "",
      "postfixFontSize": "50%",
      "prefix": "",
      "prefixFontSize": "50%",
      "rangeMaps": [
        {
          "from": "null",
          "text": "N/A",
          "to": "null"
        }
      ],
      "sparkline": {
        "fillColor": "rgba(31, 118, 189, 0.18)",
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "show": false
      },
      "tableColumn": "",
      "targets": [
        {
          "expr": "ucs_server_count",
          "format": "time_series",
          "intervalFactor": 1,
          "refId": "A"
        }
      ],
      "thresholds": "",
      "title": "Servers",
      "type": "singlestat",
      "valueFontSize": "80%",
      "valueMaps": [
        {
          "op": "=",
          "text": "N/A",
          "value": "null"
        }
      ],
      "valueName": "current"
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "fill": 1,
      "gridPos": {
        "h": 9,
        "w": 11,
        "x": 0,
        "y": 19
      },
      "id": 4,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "node_load1",
          "intervalFactor": 1,
          "format": "time_series",
          "refId": "A",
          "legendFormat": "{{instance}}",
          "interval": ""
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "CPU Usage",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "folderId": 0,
      "gridPos": {
        "h": 8,
        "w": 7,
        "x": 0,
        "y": 1
      },
      "headings": false,
      "id": 2,
      "limit": 0,
      "query": "",
      "recent": false,
      "search": true,
      "starred": false,
      "tags": [],
      "title": "Available Dashboards",
      "type": "dashlist"
    },
    {
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "id": 20,
      "panels": [],
      "title": "Domain Overview",
      "type": "row"
    },
    {
      "cacheTimeout": null,
      "colorBackground": false,
      "colorValue": true,
      "colors": [
        "#299c46",
        "rgba(237, 129, 40, 0.89)",
        "#d44a3a"
      ],
      "datasource": "Univention",
      "format": "none",
      "gauge": {
        "maxValue": 100,
        "minValue": 0,
        "show": false,
        "thresholdLabels": false,
        "thresholdMarkers": true
      },
      "gridPos": {
        "h": 2,
        "w": 5,
        "x": 17,
        "y": 1
      },
      "id": 14,
      "interval": null,
      "links": [
        {
          "targetBlank": true,
          "title": "Benefits of our Enterprise Subscriptions at a glance",
          "type": "absolute",
          "url": "https://www.univention.com/products/benefits-ucs-enterprise-subscriptions-for-restricted-apps/"
        }
      ],
      "mappingType": 1,
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "maxDataPoints": 100,
      "nullPointMode": "connected",
      "nullText": null,
      "postfix": "",
      "postfixFontSize": "50%",
      "prefix": "",
      "prefixFontSize": "50%",
      "rangeMaps": [
        {
          "from": "null",
          "text": "N/A",
          "to": "null"
        }
      ],
      "sparkline": {
        "fillColor": "rgba(31, 118, 189, 0.18)",
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "show": false
      },
      "tableColumn": "",
      "targets": [
        {
          "expr": "ucs_license",
          "format": "time_series",
          "intervalFactor": 1,
          "refId": "A"
        }
      ],
      "thresholds": "2,2",
      "title": "UCS License",
      "type": "singlestat",
      "valueFontSize": "50%",
      "valueMaps": [
        {
          "op": "=",
          "text": "Core Edition",
          "value": "2"
        },
        {
          "op": "=",
          "text": "Enterprise Subscription",
          "value": "1"
        }
      ],
      "valueName": "current"
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "fill": 1,
      "gridPos": {
        "h": 9,
        "w": 11,
        "x": 11,
        "y": 19
      },
      "id": 18,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "node_memory_MemAvailable_bytes",
          "intervalFactor": 1,
          "format": "time_series",
          "refId": "A",
          "legendFormat": "{{instance}}"
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Memory available",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "bytes",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "type": "graph",
      "title": "UCS LDAP Replication - Notifier ID",
      "gridPos": {
        "h": 9,
        "w": 11,
        "x": 11,
        "y": 28
      },
      "id": 30,
      "datasource": null,
      "targets": [
        {
          "expr": "ucs_notifier_id",
          "intervalFactor": 1,
          "format": "time_series",
          "refId": "A",
          "legendFormat": "{{instance}}"
        }
      ],
      "renderer": "flot",
      "yaxes": [
        {
          "label": null,
          "show": true,
          "logBase": 1,
          "min": null,
          "max": null,
          "format": "short"
        },
        {
          "label": null,
          "show": true,
          "logBase": 1,
          "min": null,
          "max": null,
          "format": "short"
        }
      ],
      "xaxis": {
        "show": true,
        "mode": "time",
        "name": null,
        "values": [],
        "buckets": null
      },
      "yaxis": {
        "align": false,
        "alignLevel": null
      },
      "lines": true,
      "fill": 1,
      "linewidth": 1,
      "dashes": false,
      "dashLength": 10,
      "spaceLength": 10,
      "points": false,
      "pointradius": 5,
      "bars": false,
      "stack": false,
      "percentage": false,
      "legend": {
        "show": true,
        "values": false,
        "min": false,
        "max": false,
        "current": false,
        "total": false,
        "avg": false
      },
      "nullPointMode": "null",
      "steppedLine": false,
      "tooltip": {
        "value_type": "individual",
        "shared": true,
        "sort": 0
      },
      "timeFrom": null,
      "timeShift": null,
      "aliasColors": {},
      "seriesOverrides": [],
      "thresholds": [],
      "links": [],
      "description": "The UCS LDAP Replication listener/notifier mechanism works based on transactions. A transaction ID is increased for every change in the LDAP directory of the master domain controller. A Univention Directory Listener instance which has missed several transactions - for example, because the computer was switched off - automatically requests all the missing transactions once the connection is available again until its local transaction ID corresponds to that of the master domain controller."
    },
    {
      "type": "singlestat",
      "title": "Dashboard Database Size",
      "gridPos": {
        "h": 2,
        "w": 5,
        "x": 17,
        "y": 3
      },
      "id": 28,
      "datasource": "Univention",
      "targets": [
        {
          "expr": "prometheus_data_directory_size_bytes",
          "intervalFactor": 1,
          "format": "time_series",
          "refId": "A",
          "legendFormat": "{{instance}}",
          "interval": ""
        }
      ],
      "links": [],
      "maxDataPoints": 100,
      "interval": null,
      "cacheTimeout": null,
      "format": "bytes",
      "prefix": "",
      "postfix": "",
      "nullText": null,
      "valueMaps": [
        {
          "value": "null",
          "op": "=",
          "text": "N/A"
        }
      ],
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "rangeMaps": [
        {
          "from": "null",
          "to": "null",
          "text": "N/A"
        }
      ],
      "mappingType": 1,
      "nullPointMode": "connected",
      "valueName": "current",
      "prefixFontSize": "50%",
      "valueFontSize": "80%",
      "postfixFontSize": "50%",
      "thresholds": "",
      "colorBackground": false,
      "colorValue": false,
      "colors": [
        "#299c46",
        "rgba(237, 129, 40, 0.89)",
        "#d44a3a"
      ],
      "sparkline": {
        "show": true,
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "fillColor": "rgba(31, 118, 189, 0.18)"
      },
      "gauge": {
        "show": false,
        "minValue": 0,
        "maxValue": 100,
        "thresholdMarkers": true,
        "thresholdLabels": false
      },
      "tableColumn": "",
      "repeat": null,
      "repeatDirection": "h",
      "description": "Size of the prometheus database directory /var/lib/univention-appcenter/apps/prometheus/data."
    },
    {
      "type": "graph",
      "title": "Free disk space on /",
      "gridPos": {
        "h": 9,
        "w": 11,
        "x": 0,
        "y": 28
      },
      "id": 26,
      "datasource": "Univention",
      "targets": [
        {
          "expr": "node_filesystem_free_bytes{mountpoint=\"/\"}",
          "intervalFactor": 1,
          "format": "time_series",
          "refId": "A",
          "legendFormat": "{{instance}}"
        }
      ],
      "renderer": "flot",
      "yaxes": [
        {
          "label": null,
          "show": true,
          "logBase": 1,
          "min": null,
          "max": null,
          "format": "bytes"
        },
        {
          "label": null,
          "show": true,
          "logBase": 1,
          "min": null,
          "max": null,
          "format": "short"
        }
      ],
      "xaxis": {
        "show": true,
        "mode": "time",
        "name": null,
        "values": [],
        "buckets": null
      },
      "yaxis": {
        "align": false,
        "alignLevel": null
      },
      "lines": true,
      "fill": 1,
      "linewidth": 1,
      "dashes": false,
      "dashLength": 10,
      "spaceLength": 10,
      "points": false,
      "pointradius": 5,
      "bars": false,
      "stack": false,
      "percentage": false,
      "legend": {
        "show": true,
        "values": false,
        "min": false,
        "max": false,
        "current": false,
        "total": false,
        "avg": false
      },
      "nullPointMode": "null",
      "steppedLine": false,
      "tooltip": {
        "value_type": "individual",
        "shared": true,
        "sort": 0
      },
      "timeFrom": null,
      "timeShift": null,
      "aliasColors": {},
      "seriesOverrides": [],
      "thresholds": [],
      "links": []
    },
    {
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 18
      },
      "id": 16,
      "panels": [],
      "title": "Server Overview",
      "type": "row"
    },
    {
      "columns": [],
      "datasource": "Univention",
      "fontSize": "100%",
      "gridPos": {
        "h": 9,
        "w": 22,
        "x": 0,
        "y": 9
      },
      "id": 22,
      "links": [],
      "pageSize": null,
      "scroll": true,
      "showHeader": true,
      "sort": {
        "col": 4,
        "desc": true
      },
      "styles": [
        {
          "alias": "",
          "colorMode": null,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "decimals": 2,
          "mappingType": 1,
          "pattern": "Time",
          "thresholds": [],
          "type": "hidden",
          "unit": "short"
        },
        {
          "alias": "",
          "colorMode": null,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "decimals": 2,
          "mappingType": 1,
          "pattern": "__name__",
          "thresholds": [],
          "type": "hidden",
          "unit": "short"
        },
        {
          "alias": "System",
          "colorMode": "cell",
          "colors": [
            "#cffaff",
            "rgba(237, 129, 40, 0.89)",
            "#629e51"
          ],
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "decimals": 2,
          "link": true,
          "linkTargetBlank": true,
          "linkTooltip": "Open UMC",
          "linkUrl": "https://${__cell}/",
          "mappingType": 1,
          "pattern": "instance",
          "sanitize": false,
          "thresholds": [],
          "type": "hidden",
          "unit": "short",
          "valueMaps": []
        },
        {
          "alias": "",
          "colorMode": null,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "decimals": 2,
          "mappingType": 1,
          "pattern": "job",
          "thresholds": [],
          "type": "hidden",
          "unit": "short"
        },
        {
          "alias": "Last Check",
          "colorMode": null,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "decimals": 2,
          "mappingType": 1,
          "pattern": "Value",
          "sanitize": false,
          "thresholds": [],
          "type": "date",
          "unit": "short"
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "System",
          "decimals": 2,
          "colors": [
            "#badff4",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": "cell",
          "pattern": "a100_name",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1,
          "link": true,
          "linkTargetBlank": true,
          "linkUrl": "https://${__cell}/univention/management/",
          "linkTooltip": "Open UMC"
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "UCS Version",
          "decimals": 2,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": null,
          "pattern": "a200_version",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "UCS Role",
          "decimals": 2,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": null,
          "pattern": "a300_ucs_role",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "Update",
          "decimals": 2,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": null,
          "pattern": "a400_update_available",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1,
          "link": true,
          "linkUrl": "https://${__cell_2}/univention/management/#module=updater",
          "linkTooltip": "Open Updater",
          "linkTargetBlank": true,
          "preserveFormat": false,
          "valueMaps": [
            {
              "value": "yes",
              "text": "update available"
            },
            {
              "value": "no",
              "text": "no update available"
            }
          ],
          "sanitize": false
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "Installed Apps",
          "decimals": 2,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": null,
          "pattern": "a500_installed_apps",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1,
          "link": true,
          "linkUrl": "https://${__cell_2}/univention/management/#module=appcenter:appcenter",
          "linkTooltip": "Open AppCenter",
          "sanitize": true
        },
        {
          "unit": "short",
          "type": "string",
          "alias": "Upgradable Apps",
          "decimals": 2,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "colorMode": null,
          "pattern": "a600_upgradable_apps",
          "dateFormat": "YYYY-MM-DD HH:mm:ss",
          "thresholds": [],
          "mappingType": 1,
          "link": true,
          "linkTargetBlank": true,
          "linkUrl": "https://${__cell_2}/univention/management/#module=appcenter:appcenter",
          "linkTooltip": "Open AppCenter",
          "sanitize": true
        },
        {
          "alias": "",
          "colorMode": null,
          "colors": [
            "rgba(245, 54, 54, 0.9)",
            "rgba(237, 129, 40, 0.89)",
            "rgba(50, 172, 45, 0.97)"
          ],
          "decimals": 2,
          "pattern": "/.*/",
          "thresholds": [],
          "type": "hidden",
          "unit": "short"
        }
      ],
      "targets": [
        {
          "expr": "univention_server_info",
          "format": "table",
          "instant": true,
          "interval": "",
          "intervalFactor": 1,
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Server info",
      "transform": "table",
      "type": "table",
      "transparent": false
    },
    {
      "cacheTimeout": null,
      "colorBackground": false,
      "colorValue": false,
      "colors": [
        "#299c46",
        "rgba(237, 129, 40, 0.89)",
        "#d44a3a"
      ],
      "datasource": "Univention",
      "format": "none",
      "gauge": {
        "maxValue": 100,
        "minValue": 0,
        "show": false,
        "thresholdLabels": false,
        "thresholdMarkers": true
      },
      "gridPos": {
        "h": 2,
        "w": 3,
        "x": 7,
        "y": 1
      },
      "id": 6,
      "interval": null,
      "links": [
        {
          "includeVars": false,
          "targetBlank": true,
          "title": "Link to user administration",
          "type": "absolute",
          "url": "http://${ldap_master}/univention/management/#module=udm:users/user:0:"
        }
      ],
      "mappingType": 1,
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "maxDataPoints": 100,
      "nullPointMode": "connected",
      "nullText": null,
      "postfix": "",
      "postfixFontSize": "50%",
      "prefix": "",
      "prefixFontSize": "50%",
      "rangeMaps": [
        {
          "from": "null",
          "text": "N/A",
          "to": "null"
        }
      ],
      "sparkline": {
        "fillColor": "rgba(31, 118, 189, 0.18)",
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "show": true
      },
      "tableColumn": "",
      "targets": [
        {
          "expr": "ucs_user_count",
          "format": "time_series",
          "interval": "",
          "intervalFactor": 1,
          "legendFormat": "",
          "refId": "A"
        },
        {
          "expr": "",
          "format": "time_series",
          "intervalFactor": 1,
          "refId": "B"
        }
      ],
      "thresholds": "",
      "title": "Domain Users",
      "type": "singlestat",
      "valueFontSize": "80%",
      "valueMaps": [
        {
          "op": "=",
          "text": "N/A",
          "value": "null"
        }
      ],
      "valueName": "current"
    }
  ]
}
EOF

# dashboard provisioning
cat << "EOF" > /var/lib/univention-appcenter/apps/$app_id/data/provisioning/dashboards/server-dashboard.json
{
  "annotations": {
    "list": [
      {
        "$$hashKey": "object:981",
        "builtIn": 1,
        "datasource": "-- Grafana --",
        "enable": true,
        "hide": true,
        "iconColor": "rgba(0, 211, 255, 1)",
        "name": "Annotations & Alerts",
        "type": "dashboard"
      }
    ]
  },
  "editable": false,
  "tags": [ "templated" ],
  "graphTooltip": 1,
  "id": null,
  "links": [],
  "timezone": "browser",
  "title": "Server Dashboard",
  "version": 1,
  "uid": "univention-server-dashboard",
  "panels": [
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 0,
        "y": 0
      },
      "id": 8,
      "isNew": true,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [
        {
          "alias": "Load",
          "color": "#DEDAF7",
          "fill": 0,
          "stack": false,
          "yaxis": 2
        }
      ],
      "spaceLength": 10,
      "stack": true,
      "steppedLine": false,
      "targets": [
        {
          "expr": "sum(irate(node_cpu{mode!=\"idle\", instance=\"$server\"}[5m])) by (mode)",
          "intervalFactor": 2,
          "legendFormat": "{{mode}}",
          "metric": "node_",
          "refId": "A",
          "step": 10
        },
        {
          "expr": "node_load1{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "Load",
          "refId": "B",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "CPU",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "percentunit",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "none",
          "label": "Load",
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 12,
        "y": 0
      },
      "id": 2,
      "isNew": true,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [
        {
          "alias": "/.+ receive/",
          "transform": "negative-Y"
        }
      ],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "irate(node_network_receive_bytes_total{instance=\"$server\"}[2m])",
          "intervalFactor": 2,
          "legendFormat": "{{device}} receive",
          "metric": "node_network_receive_bytes_total",
          "refId": "A",
          "step": 10
        },
        {
          "expr": "irate(node_network_transmit_bytes_total{instance=\"$server\"}[2m])",
          "intervalFactor": 2,
          "legendFormat": "{{device}} transmit",
          "metric": "node_network_transmit_bytes_total",
          "refId": "B",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Network",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "Bps",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {
        "Free": "#70DBED"
      },
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 0,
        "y": 7
      },
      "id": 4,
      "isNew": true,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [
        {
          "alias": "Cached",
          "color": "#64B0C8"
        }
      ],
      "spaceLength": 10,
      "stack": true,
      "steppedLine": false,
      "targets": [
        {
          "expr": "node_memory_MemTotal_bytes{instance=\"$server\"} - node_memory_MemFree_bytes{instance=\"$server\"} - node_memory_Buffers_bytes{instance=\"$server\"} - node_memory_Cached_bytes{instance=\"$server\"}",
          "hide": false,
          "intervalFactor": 2,
          "legendFormat": "Used",
          "metric": "node_memory_MemFree_bytes",
          "refId": "A",
          "step": 10
        },
        {
          "expr": "node_memory_Buffers_bytes{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "Buffered",
          "metric": "node_memory_Buffers_bytes",
          "refId": "D",
          "step": 10
        },
        {
          "expr": "node_memory_Cached_bytes{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "Cached",
          "metric": "node_memory_SwapFree_bytes",
          "refId": "B",
          "step": 10
        },
        {
          "expr": "node_memory_MemFree_bytes{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "Free",
          "metric": "node_memory_MemTotal_bytes",
          "refId": "C",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Memory",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "bytes",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 12,
        "y": 7
      },
      "id": 5,
      "isNew": true,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [
        {
          "alias": "/.* written/",
          "transform": "negative-Y"
        }
      ],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "irate(node_disk_read_bytes_total{instance=\"$server\"}[2m])",
          "hide": false,
          "intervalFactor": 2,
          "legendFormat": "{{device}} read",
          "metric": "node_disk_read_bytes_total",
          "refId": "B",
          "step": 10
        },
        {
          "expr": "irate(node_disk_written_bytes_total{instance=\"$server\"}[2m])",
          "hide": false,
          "intervalFactor": 2,
          "legendFormat": "{{device}} written",
          "metric": "node_disk_",
          "refId": "C",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Disk thoughput",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "Bps",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "ms",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 0,
        "y": 14
      },
      "id": 6,
      "isNew": true,
      "legend": {
        "alignAsTable": false,
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "rightSide": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [
        {
          "alias": "/.* io time/",
          "yaxis": 2
        }
      ],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "node_disk_io_now{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "{{device}}",
          "metric": "node_disk_io",
          "refId": "A",
          "step": 10
        },
        {
          "expr": "irate(node_disk_io_time_seconds_total{instance=\"$server\"}[2m]) * 1000",
          "intervalFactor": 2,
          "legendFormat": "{{device}} io time",
          "metric": "node_disk_io_time_seconds_total",
          "refId": "B",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Disk IO",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "iops",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "ms",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Univention",
      "editable": true,
      "error": false,
      "fill": 1,
      "grid": {},
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 12,
        "y": 14
      },
      "id": 7,
      "isNew": true,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 2,
      "links": [],
      "nullPointMode": "connected",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "(node_filesystem_size_bytes{instance=\"$server\"} - node_filesystem_avail_bytes{instance=\"$server\"})/ node_filesystem_size_bytes{instance=\"$server\"}",
          "intervalFactor": 2,
          "legendFormat": "{{mountpoint}}",
          "metric": "node_filesystem_size_bytes",
          "refId": "A",
          "step": 10
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeShift": null,
      "title": "Disk usage",
      "tooltip": {
        "msResolution": false,
        "shared": true,
        "sort": 0,
        "value_type": "cumulative"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "percentunit",
          "label": "",
          "logBase": 1,
          "max": "1",
          "min": "0",
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    }
  ],
  "refresh": "30s",
  "schemaVersion": 16,
  "style": "dark",
  "templating": {
    "list": [
      {
        "allValue": null,
        "current": {
          "isNone": true,
          "text": "None",
          "value": ""
        },
        "datasource": "Univention",
        "hide": 0,
        "includeAll": false,
        "label": null,
        "multi": false,
        "name": "server",
        "options": [],
        "query": "label_values(node_boot_time_seconds, instance)",
        "refresh": 2,
        "regex": "",
        "sort": 0,
        "tagValuesQuery": null,
        "tags": [],
        "tagsQuery": null,
        "type": "query",
        "useTags": false
      }
    ]
  },
  "time": {
    "from": "now-24h",
    "to": "now"
  },
  "timepicker": {
    "nowDelay": "5m",
    "refresh_intervals": [
      "5s",
      "10s",
      "30s",
      "1m",
      "5m",
      "15m",
      "30m",
      "1h",
      "2h",
      "1d"
    ],
    "time_options": [
      "5m",
      "15m",
      "1h",
      "6h",
      "12h",
      "24h",
      "2d",
      "7d",
      "30d"
    ]
  }
}
EOF

# dashboard provisioning
cat << "EOF" > /var/lib/univention-appcenter/apps/$app_id/data/provisioning/dashboards/alert-dashboard.json
{
    "__elements": [],
    "__inputs": [
        {
            "description": "",
            "label": "Univention",
            "name": "DS_UNIVENTION",
            "pluginId": "prometheus",
            "pluginName": "Prometheus",
            "type": "datasource"
        }
    ],
    "__requires": [
        {
            "id": "alertlist",
            "name": "Alert list",
            "type": "panel",
            "version": ""
        },
        {
            "id": "grafana",
            "name": "Grafana",
            "type": "grafana",
            "version": "8.5.2"
        },
        {
            "id": "prometheus",
            "name": "Prometheus",
            "type": "datasource",
            "version": "1.0.0"
        }
    ],
    "annotations": {
        "list": [
            {
                "builtIn": 1,
                "datasource": {
                    "type": "grafana",
                    "uid": "-- Grafana --"
                },
                "enable": true,
                "hide": true,
                "iconColor": "rgba(0, 211, 255, 1)",
                "name": "Annotations & Alerts",
                "target": {
                    "limit": 100,
                    "matchAny": false,
                    "tags": [],
                    "type": "dashboard"
                },
                "type": "dashboard"
            }
        ]
    },
    "description": "Overview of all Univention alerts",
    "editable": false,
    "fiscalYearStartMonth": 0,
    "graphTooltip": 1,
    "id": null,
    "links": [],
    "liveNow": false,
    "panels": [
        {
            "datasource": {
                "type": "prometheus",
                "uid": "${DS_UNIVENTION}"
            },
            "description": "Overview of all Univention alerts",
            "gridPos": {
                "h": 31,
                "w": 16,
                "x": 0,
                "y": 0
            },
            "id": 2,
            "options": {
                "alertInstanceLabelFilter": "",
                "alertName": "",
                "dashboardAlerts": false,
                "datasource": "Univention",
                "groupBy": [],
                "groupMode": "default",
                "maxItems": 200,
                "sortOrder": 4,
                "stateFilter": {
                    "error": true,
                    "firing": true,
                    "inactive": true,
                    "noData": true,
                    "normal": true,
                    "pending": true
                }
            },
            "title": "Alert Status",
            "type": "alertlist"
        }
    ],
    "refresh": "30s",
    "schemaVersion": 36,
    "style": "dark",
    "tags": ["templated"],
    "templating": {
        "list": []
    },
    "time": {
        "from": "now-24h",
        "to": "now"
    },
    "timepicker": {},
    "timezone": "browser",
    "title": "Alert Dashboard",
    "uid": "univention-alert-dashboard",
    "version": 1,
    "weekStart": ""
}
EOF

# update root ca
docker cp /etc/univention/ssl/ucsCA/CAcert.pem $(ucr get appcenter/apps/$app_id/container):/usr/local/share/ca-certificates/ucs.crt
docker exec -u root $(ucr get appcenter/apps/$app_id/container) update-ca-certificates --fresh

docker restart "$(ucr get appcenter/apps/$app_id/container)"

exit 0
