//     Sofaraum client is the client software which collects statistics about
//     wifi devices nearby and then sends them to the Sofaraum Server.
//     Copyright (c) 2018.
//
//     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 <https://www.gnu.org/licenses/>.

package cmd

import (
	"git.kolaente.de/sofaraum/client/pkg/processing"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"log"
	"net/http"
)

// daemonCmd represents the daemon command
var daemonCmd = &cobra.Command{
	Use:   "daemon",
	Short: "Runs the sofa daemon which constantly parses airodump-ng csv dumps and sends the results to the server.",
	Long:  `The sofa daemon parses csv dumps produced by airodump-ng and sends the aggregated results to the sofa server.`,
	Run: func(cmd *cobra.Command, args []string) {

		// Send the daemon process in the background if we want a metrics endpoint
		if viper.GetBool("daemon.enableemetricsendpoint") {
			go processing.SummonTheDaemon()

			processing.RecordMetrics()
			http.Handle("/metrics", promhttp.Handler())
			err := http.ListenAndServe(viper.GetString("daemon.metricsinterface"), nil)
			if err != nil {
				log.Fatal(err)
			}
		} else {
			// Start the daemon directly
			processing.SummonTheDaemon()
		}
	},
}

func init() {
	rootCmd.AddCommand(daemonCmd)

	// Flags
	daemonCmd.Flags().StringP("csvlocation", "c", "/opt/sofadaemon", "The location of the airodump-ng csv dumps")
	viper.BindPFlag("daemon.csvlocation", daemonCmd.Flags().Lookup("csvlocation"))
	daemonCmd.Flags().StringP("wifidevice", "w", "wlan0", "The wifi interface with which to collect wifi statistics")
	viper.BindPFlag("daemon.wifidevice", daemonCmd.Flags().Lookup("wifidevice"))

	daemonCmd.Flags().BoolP("metricsendpoint", "m", false, "Enable a /metrics endpoint for prometheus to pull the currently active clients")
	viper.BindPFlag("daemon.enableemetricsendpoint", daemonCmd.Flags().Lookup("metricsendpoint"))
	daemonCmd.Flags().StringP("metricsinterface", "", ":2112", "The port with interface under which the metrics endpoint should be available")
	viper.BindPFlag("daemon.metricsinterface", daemonCmd.Flags().Lookup("metricsinterface"))
}
