package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

type event struct {
	ServiceKey  string       `json:"service_key"`
	EventType   string       `json:"event_type"`
	Description string       `json:"description"`
	Details     eventDetails `json:"details"`
	ClientURL   string       `json:"client_url"`
}

type eventDetails struct {
	Commit  string `json:"commit"`
	BuildID string `json:"build_id"`
}

func main() {
	pagerDutyURL := os.Args[1]

	bs := bytes.NewBuffer(nil)

	if err := json.NewEncoder(bs).Encode(event{
		ServiceKey: os.Getenv("PAGERDUTY_KEY"),
		EventType:  "trigger",
		Description: fmt.Sprintf(
			"Production Deployment Failed - %s %s",
			os.Getenv("JOB_NAME"),
			os.Getenv("BUILD_DISPLAY_NAME"),
		),
		Details: eventDetails{
			Commit:  os.Getenv("GIT_COMMIT"),
			BuildID: os.Getenv("BUILD_ID"),
		},
		ClientURL: os.Getenv("BUILD_URL"),
	}); err != nil {
		log.Fatal(err)
	}

	resp, err := http.Post(pagerDutyURL, "application/json", bs)

	if err != nil {
		log.Fatal(err)
	}

	if resp.StatusCode != http.StatusOK {
		log.Fatal(fmt.Errorf("Invalid response from endpoint"))
	}
}
