package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"

	"src.opensuse.org/autogits/common"
)

const (
	ListenAddr = "[::1]:8002"
	AppName    = "rabbitmq-forwarder"
)

var DebugMode bool

func connectToRabbitMQ() {
	host := os.Getenv("RABBITMQ_HOST")
	username := os.Getenv("RABBITMQ_USERNAME")
	password := os.Getenv("RABBITMQ_PASSWORD")

	if len(host) == 0 || len(username) == 0 || len(password) == 0 {
		fmt.Println("Missing RABBITMQ_HOST, RABBITMQ_USERNAME, RABBITMQ_PASSWORD")
		os.Exit(1)
	}

	go ConnectToExchangeForPublish(host, username, password)
}

func main() {
	flag.BoolVar(&DebugMode, "debug", false, "enables debugging messages")
	flag.Parse()

	connectToRabbitMQ()

	http.HandleFunc("POST /rabbitmq-forwarder/{Org}", func(res http.ResponseWriter, req *http.Request) {
		if len(req.Header.Get("Content-Type")) == 0 ||
			req.Header["Content-Type"][0] != "application/json" ||
			req.Method != "POST" {

			res.WriteHeader(http.StatusInternalServerError)
			return
		}

		hdr := req.Header[common.GiteaRequestHeader]
		if len(hdr) != 1 {
			res.WriteHeader(http.StatusInternalServerError)
			log.Printf("Multiple Gitea headers received. %#v\n", hdr)
			if DebugMode {
				log.Println(req.Header)
			}
			return
		}
		reqType := hdr[0]
		err := PublicMessage(reqType, req.PathValue("Org"), req.Body)
		if err != nil {
			log.Printf("hook (%s) processing error: %v\n", reqType, err)
			res.WriteHeader(http.StatusBadRequest)
		} else {
			res.WriteHeader(http.StatusOK)
		}
	})

	log.Fatal(http.ListenAndServe(ListenAddr, nil))
}
