#!/bin/sh

export GOBIN=/opt/gocode/bin  # where to find go binaries

exporter="$(cat "$__object/parameter/exporter")"
[ -z "$exporter" ] && exporter="$__object_id"

__user prometheus
require="__user/prometheus" __group prometheus
require="__group/prometheus" __user_groups prometheus --group prometheus

require="__user_groups/prometheus"
case $exporter in
	node)
		TEXTFILES=/service/node-exporter/textfiles  # path for the textfiles collector
		__directory $TEXTFILES --parents --mode 777
		require="$require __golang_from_vendor" __go_get github.com/prometheus/node_exporter

		port=9100
		run="setuidgid prometheus $GOBIN/node_exporter -web.listen-address :$port -collector.textfile.directory=$TEXTFILES"
	;;
	blackbox)
		require="$require __daemontools_service/${exporter}-exporter __user/prometheus" __config_file "/service/${exporter}-exporter/blackbox.yml" \
			--source "$__type/files/blackbox.yml" \
			--group prometheus --mode 640 \
			--onchange "svc -h /service/${exporter}-exporter"
		require="$require __golang_from_vendor" __go_get github.com/prometheus/blackbox_exporter

		port=9115
		run="setuidgid prometheus $GOBIN/blackbox_exporter -config.file=/service/${exporter}-exporter/blackbox.yml"
	;;
	ceph)
		__package librados-dev  # dependency of ceph_exporter
		require="$require __golang_from_vendor __package/librados-dev" __go_get github.com/digitalocean/ceph_exporter

		port=9128
		run="setuidgid ceph $GOBIN/ceph_exporter -ceph.config /etc/ceph/ceph.conf -telemetry.addr :$port"
	;;
	*)
		echo "Unsupported exporter: $exporter." >&2
		exit 1
	;;
esac

require="$require __daemontools" __daemontools_service "${exporter}-exporter" --run "$run"
if [ -f "$__object/parameter/add-consul-service" ]; then
	__consul_service "${exporter}-exporter" --port "$port" --check-http "http://localhost:$port/metrics" --check-interval 10s
fi

#__daemontools --install-init-script
__daemontools
__golang_from_vendor --version 1.9  # required for many exporters
