#!/bin/bash

if [ -z "$INFLUX_TOKEN" ]; then
  echo "WARNING: You need to set an INFLUX_TOKEN environment variable or else it won't actually work."
fi

# This is hardcoded here because it's easier.  Find it on your own. :-)
PPBAkey="00e086b2-85b9-4562-a6bd-6d5a68ad2c26"
fluxHost="192.168.0.6"
fluxPort="8086"
ppbaHost="192.168.0.151"
ppbaPort="32000"

do_help() {
  echo "Help coming soon.  I promise.  Do not panic!"
  exit
}

do_preface() {
  cat << PREFACE_EOF
[global_tags]

[agent]
  interval = "10s"
  round_interval = true
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  collection_jitter = "0s"
  flush_interval = "10s"
  flush_jitter = "0s"
  precision = "0s"

[[outputs.influxdb_v2]]
  urls = ["http://${fluxHost}:${fluxPort}"]
  token = "$INFLUX_TOKEN"
  organization = "Astropotamus"
  bucket = "AstropotaPOD"
PREFACE_EOF
}

do_postface() {
  cat << POSTFACE_EOF
POSTFACE_EOF
}

do_ppba() {
  do_preface
  cat << PPBA_EOF
[[inputs.http]]
  urls = [
    "http://${ppbaHost}:${ppbaPort}/Driver/PPBAdvance/Report?DriverUniqueKey=${PPBAkey}"
  ]
  name_override = "PPBA"
  data_format = "json"
  tagexclude = ["url", "host"]
  json_query="data.message"
  json_string_fields=["dewHubStatus_hub_?_current_isOverCurrent","powerHubStatus_state","powerVariablePortStatus_state"]
PPBA_EOF
  do_postface
}

do_weather() {
  do_preface
  cat << WEATHER_EOF
[[inputs.http]]
  urls=["https://api.openweathermap.org/data/2.5/weather?id=5126015&units=metric&appid=043d58f75a4ffe7cf5d414ead183cb7f"]
  data_format = "json"
  tag_keys = [ "coord_lon", "coord_lat", "sys_country", "id", "name" ]
  json_string_fields = [ "weather_0_main", "weather_0_description" ]
  json_time_key = "dt"
  json_time_format = "unix"
  name_override = "openweathermap"
WEATHER_EOF
  do_postface
}

do_local() {
  do_preface
  cat << LOCAL_EOF
[[inputs.cpu]]
  percpu = true
  totalcpu = true
  collect_cpu_time = false
  report_active = false
  core_tags = false
[[inputs.mem]]
[[inputs.system]]
LOCAL_EOF
  do_postface
}

tmpFile=$(mktemp)
while [ -n "$1" ]; do
  case "$1" in
    -h|--help) do_help;;
    --ppba) do_ppba > $tmpFile; shift 1;;
    --weather) do_weather > $tmpFile; shift 1;;
    --iss) rm $tmpFile; echo "Not yet."; exit;;
    --local) do_local > $tmpFile; shift 1;;
    *) shift 1;;
  esac
done
telegraf --config $tmpFile --once --quiet 
rm $tmpFile
