package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

func run() error {
	key := "QUOTAGUARDSTATIC_URL"
	if os.Getenv("QG_PRODUCT") == "shield" {
		key = "QUOTAGUARDSHIELD_URL"
	}
	proxy, err := url.Parse(os.Getenv(key))
	if err != nil || proxy.Host == "" || proxy.User == nil {
		return fmt.Errorf("proxy required")
	}
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.Proxy = http.ProxyURL(proxy)
	defer transport.CloseIdleConnections()
	c := &http.Client{Transport: transport, Timeout: 30 * time.Second,
		CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
	r, err := c.Get("https://ip.quotaguard.com")
	if err != nil {
		return fmt.Errorf("request failed")
	}
	defer r.Body.Close()
	if r.StatusCode != 200 {
		return fmt.Errorf("unexpected status")
	}
	var body struct {
		IP string `json:"ip"`
	}
	if json.NewDecoder(r.Body).Decode(&body) != nil {
		return fmt.Errorf("invalid JSON")
	}
	pair := strings.Split(os.Getenv("QG_EXPECTED_IPS"), ",")
	if len(pair) != 2 || strings.TrimSpace(pair[0]) == strings.TrimSpace(pair[1]) {
		return fmt.Errorf("dashboard pair required")
	}
	if body.IP != strings.TrimSpace(pair[0]) && body.IP != strings.TrimSpace(pair[1]) {
		return fmt.Errorf("wrong IP")
	}
	return nil
}
func main() {
	if run() != nil {
		fmt.Fprintln(os.Stderr, "Go proxy check failed")
		os.Exit(1)
	}
	fmt.Println("Go client egress matches dashboard pair")
}
