// Copyright (C) 2020 Emanuele Rocca <ema@wikimedia.org>
// Copyright (C) 2020 Wikimedia Foundation, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"gerrit.wikimedia.org/r/operations/software/prometheus-rdkafka-exporter/promrdkafka"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	jsonfile := flag.String("jsonfile", "/tmp/producer.json", "File with JSON stats produced by rdkafka")
	addr := flag.String("addr", ":2112", "TCP network address for prometheus metrics")
	flag.Parse()

	m := promrdkafka.NewMetrics()

	go func() {
		for {
			stats, err := ioutil.ReadFile(*jsonfile)
			if err != nil {
				panic(err)
			}
			// Keep on calling updateStats till the end of times
			err = m.Update(string(stats))
			if err != nil {
				panic(err)
			}

			time.Sleep(1000 * time.Millisecond)
		}
	}()

	fmt.Printf("Listening on :%s\n", *addr)
	http.Handle("/metrics", promhttp.Handler())
	http.ListenAndServe(*addr, nil)
}
