require stdlib
require concat

class eid::telegraf(String $version = "stable", Array $volumes = [], Array $ports = []) {
   $influxdb2_token = hiera("influxdb2_token","NOT_SET_IN_HIERA");
   $influx2_token = hiera("influx2_token","NOT_SET_IN_HIERA");
   $influxdb2_org = hiera("influxdb2_org","NOT_SET_IN_HIERA");
   $influxdb2_bucket = hiera("influxdb2_bucket","NOT_SET_IN_HIERA");
   file {['/etc/telegraf','/etc/telegraf/telegraf.conf.d']: ensure => directory }
   concat {'/etc/telegraf/telegraf.conf':
      owner     => 'root',
      group     => 'root',
      mode      => '0644',
      notify    => Sunet::Docker_run['telegraf']
   }

   # Below not pretty but I'm piggy-backing on this class to add a secondary output to test the new influx2-server
   if ($influx2_token != 'NOT_SET_IN_HIERA') {
     file { "/etc/telegraf/telegraf.conf.d/95-telegraf.conf":
       ensure  => file,
       owner   => 'root',
       group   => 'root',
       path    => "/etc/telegraf/telegraf.conf.d/95-telegraf.conf",
       mode    => '0644',
       content => template('eid/telegraf/95-telegraf.conf.erb'),
     }
   }

   eid_glob(["/etc/telegraf/telegraf.conf.d/*.conf"]).each |String $file| {
     concat::fragment { $file:
        target => "/etc/telegraf/telegraf.conf",
        source => $file,
     }
   }

   $_volumes = flatten(["/dev/log:/dev/log","/var/log:/var/log","/etc/telegraf:/etc/telegraf","/var/run/utmp:/var/run/utmp:ro",$volumes])

   if ($influx2_token != 'NOT_SET_IN_HIERA') {
     sunet::docker_run {"telegraf":
       hostname => "${::fqdn}",
       image     => "docker.sunet.se/eduid/telegraf",
       imagetag  => "latest",
       volumes   => $_volumes,
       ports     => $ports,
       env       => ["INFLUXDB2_TOKEN=$influxdb2_token","INFLUXDB2_ORG=$influxdb2_org","INFLUXDB2_BUCKET=$influxdb2_bucket","INFLUX2_TOKEN=$influx2_token"]
     }
   } else {
     sunet::docker_run {"telegraf":
       hostname => "${::fqdn}",
       image     => "docker.sunet.se/eduid/telegraf",
       imagetag  => $version,
       volumes   => $_volumes,
       ports     => $ports,
       env       => ["INFLUXDB2_TOKEN=$influxdb2_token","INFLUXDB2_ORG=$influxdb2_org","INFLUXDB2_BUCKET=$influxdb2_bucket"]
     }
   }
}
