apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "influxdb-enterprise.fullname" . }}-meta
  labels:
    app.kubernetes.io/component: meta
    {{- include "influxdb-enterprise.labels" . | nindent 4 }}
data:
  influxdb-meta.conf: |+
    bind-address = ":8091"
    reporting-disabled = false

    [enterprise]
      {{ if .Values.license.key }}
      # license-key and license-path are mutually exclusive, use only one and leave the other blank
      license-key = "{{ .Values.license.key }}" #✨ mutually exclusive with license-path
      {{ else }}
      # license-key and license-path are mutually exclusive, use only one and leave the other blank
      license-path = "/var/run/secrets/influxdb/license.json"
      {{ end }}

    [meta]
      dir = "/var/lib/influxdb/meta"

      {{ if .Values.meta.https.enabled }}
      https-enabled = true

      https-certificate = "/var/run/secrets/tls/tls.crt"
      https-private-key = "/var/run/secrets/tls/tls.key"

      {{ if .Values.meta.https.insecure }}
      https-insecure-tls = true
      {{ end }}

      {{ end }}

      {{ if and .Values.data.https.enabled }}
      data-use-tls = true

      {{ if .Values.data.https.insecure }}
      data-insecure-tls = true
      {{ end }}

      {{ end }}

  entrypoint.pl: |+
    #!/usr/bin/env perl
    $ENV{INFLUXDB_HOSTNAME} = `hostname -f`;
    $ENV{INFLUXDB_HOSTNAME} =~ s/\n$//;

    $pid = fork();

    # Inside this conditional is our child process, which
    # will return `influxd-meta`
    if($pid == 0) {
      exec('influxd-meta') or die("Failed to execute influxd-meta: $!\n");
    }

    $SIG{HUP} = sub { kill 'HUP', $pid };
    $SIG{TERM} = sub { kill 'TERM', $pid };
    $SIG{KILL} = sub { kill 'KILL', $pid };

    # Register meta node
    my $meta_leader = $ENV{INFLUXDB_HOSTNAME};
    $meta_leader =~ s/-[0-9]+./-0./;

    # We're not going to define an exit strategy for failure here.
    # This should be handled by the probes on the pods
    while (true) {
      if($meta_leader eq $ENV{INFLUXDB_HOSTNAME}) {
        system('influxd-ctl', {{ if .Values.meta.https.enabled }}'-bind-tls',{{ end }}{{ if .Values.meta.https.insecure }}'-k',{{ end }} 'add-meta', "$ENV{INFLUXDB_HOSTNAME}:8091");
      } else {
        system('influxd-ctl', {{ if .Values.meta.https.enabled }}'-bind-tls',{{ end }}{{ if .Values.meta.https.insecure }}'-k',{{ end }} 'join', "$meta_leader:8091");
      }

      if ($? == 0) {
          last;
      }

      # Wait a few seconds and try again
      # Maybe we should implement some rudamentary backoff
      sleep(2);
    }

    waitpid($pid, 0);
    exit $?