// Copyright Jan Dittberner
// SPDX-License-Identifier: GPL-3.0-or-later
//
// 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/>.

// The main package for matrix-host-notification
package main

import (
	"flag"
	"log"
	"os"

	"git.ditberner.info/jan/icinga2-matrix-notification/internal/icinga2"
	"git.ditberner.info/jan/icinga2-matrix-notification/internal/matrix"
)

func main() {
	config := parseFlags()

	message, err := icinga2.BuildHostNotification(config)
	if err != nil {
		log.Fatalf("could not build message: %v", err)
	}

	if err := matrix.SendMessage(config.MatrixServer.URL, config.MatrixRoom, config.MatrixToken, message); err != nil {
		log.Fatalf("could not send message: %v", err)
	}
}

func parseFlags() *icinga2.HostParameters {
	config := &icinga2.HostParameters{}

	flag.StringVar(&config.LongDateTime, "d", "", "long date time ($icinga.long_date_time$)")
	flag.StringVar(&config.Hostname, "l", "", "hostname ($host.name$)")
	flag.StringVar(&config.HostDisplayName, "n", "", "host display name ($host.display_name$)")

	flag.StringVar(&config.HostOutput, "o", "", "host output ($host.output$)")
	flag.StringVar(&config.HostState, "s", "", "host state ($host.state$)")

	flag.StringVar(&config.MatrixRoom, "m", "", "matrix room ($notification_matrix_room$)")
	flag.Var(&config.MatrixServer, "x", "matrix server ($notification_matrix_server$)")
	flag.StringVar(&config.MatrixToken, "y", "", "matrix access token ($notification_matrix_token$)")

	flag.StringVar(&config.HostAddress, "4", "", "host address ($address$)")
	flag.StringVar(&config.HostAddress6, "6", "", "host address ($address6$)")
	flag.StringVar(&config.NotificationAuthorName, "b", "", "notification author name ($notification.author_name$)")
	flag.StringVar(&config.NotificationComment, "c", "", "notification comment ($notification.comment$)")
	flag.Var(&config.IcingaWeb2URL, "i", "IcingaWeb 2 URL ($notification_icingaweb2url$)")

	flag.Parse()

	if err := config.ValidateRequired(); err != nil {
		flag.Usage()

		os.Exit(2) //nolint:mnd
	}

	return config
}