package main

import (
    "fmt"
    "net/http"
    "net/url"
    "os"
    "time"
)

func run() error {
    target, err := url.Parse(os.Getenv("QG_TARGET_URL"))
    if err != nil || target.Scheme != "https" || target.Hostname() == "" || target.User != nil { return fmt.Errorf("config") }
    proxy, err := url.Parse(os.Getenv("QUOTAGUARDSTATIC_URL"))
    if err != nil || (proxy.Scheme != "http" && proxy.Scheme != "https") || proxy.Hostname() == "" || proxy.User == nil { return fmt.Errorf("config") }
    token := os.Getenv("DESTINATION_API_TOKEN")
    if token != "" && target.Hostname() == "ip.quotaguard.com" { return fmt.Errorf("config") }
    transport := &http.Transport{Proxy: http.ProxyURL(proxy), TLSHandshakeTimeout: 10 * time.Second}
    defer transport.CloseIdleConnections()
    client := &http.Client{Transport: transport, Timeout: 30 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
    req, err := http.NewRequest(http.MethodGet, target.String(), nil)
    if err != nil { return err }
    if token != "" { req.Header.Set("Authorization", "Bearer " + token) }
    response, err := client.Do(req)
    if err != nil { return err }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 { return fmt.Errorf("status") }
    return nil
}

func main() {
    if run() != nil { fmt.Fprintln(os.Stderr, "Request failed; check configuration and the guide."); os.Exit(1) }
    fmt.Println("PASS: destination returned a successful HTTP status")
}
