#
# Copyright 2020 The dNation Jsonnet Translator Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Example with build options for jsonnet compiler

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: default
  name: jsonnet-ext-cm
  labels:
    grafana_dashboard_jsonnet: "1"
  annotations:
      ext_codes: |-
        {
         "editable": "true",
         "panels": "[['panel1', 0, 0], ['panel2', 6, 0]]"
        }
      ext_vars: '{"dashboard_name": "Example dashboard with ext_vars 2"}'
      max_trace: "8"
      # Grafana dashboards excluded from update
      grafana_dashboards_skip_update: |-
        [
          "excludme.json"
        ]
      grafana_label: "grafana_dashboard=1"
data:
  example.libsonnet: |-
    local grafana = import 'grafonnet/grafana.libsonnet';
    local prometheus = grafana.prometheus;
    local graphPanel = grafana.graphPanel;

    {
      cpu(title, x, y)::
         graphPanel.new(
           title=title,
           datasource='$datasource',
           min=0,
         )
        .addTarget(prometheus.target('rate(process_cpu_seconds_total{job="apiserver"}[5m])'))
        + {gridPos: { x: x, y: y, w: 6, h: 6 }}
    }
  excludme.jsonnet: |-
    { "test": "exludeme" }
  example-dashboard-ext.jsonnet: |-
    local grafana = import 'grafonnet/grafana.libsonnet';
    local lib = import 'example.libsonnet';
    local dashboard = grafana.dashboard;
    local prometheus = grafana.prometheus;
    local template = grafana.template;
    local statPanel = grafana.statPanel;
    local graphPanel = grafana.graphPanel;

    local upCount(title, x, y) =
      statPanel.new(
        title=title,
        datasource='$datasource',
      )
      .addTarget(prometheus.target('sum(up{job="apiserver"})'))
      + {gridPos: { x: x, y: y, w: 6, h: 6 }};

    local upCountPanels = [ upCount(panel[0], panel[1], panel[2]) for panel in std.extVar('panels') ];
    local cpuPanel = lib.cpu('CPU panel', 0, 6);

    local datasourceTemplate =
      template.datasource(
        query='prometheus',
        name='datasource',
        current=null,
        label='Datasource',
      );

    dashboard.new(
      std.extVar('dashboard_name'),
      editable=std.extVar('editable'),
      refresh='10s',
      time_from='now-5m',
      uid='example-dashboard-ext',
    )
    .addTemplate(datasourceTemplate)
    .addPanels(upCountPanels + [cpuPanel])
