tf2-checker/cmd/main.go
2024-10-26 21:46:38 +02:00

108 lines
2.5 KiB
Go

package main
import (
"encoding/json"
"flag"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"github.com/rumblefrog/go-a2s"
)
type apiResponse struct {
Response struct {
Success bool `json:"success"`
UpToDate bool `json:"up_to_date"`
VersionIsListable bool `json:"version_is_listable"`
RequiredVersion int `json:"require_version"`
Message string `json:"message"`
} `json:"response"`
}
func main() {
// Steam API takes version to check if newer version is available
url := "https://api.steampowered.com/ISteamApps/UpToDateCheck/v1/?appid=440&version="
var ip string
var port int
var name string
var command string
// Defining Flags
flag.StringVar(&ip, "ip", "127.0.0.1", "Specify ip to use.")
flag.IntVar(&port, "port", 27015, "Specify port to use.")
flag.StringVar(&name, "name", "Server", "Specify Server Name to use in the Webhook.")
flag.StringVar(&command, "command", "", "Specify Command to run if the Server is not on the newest Version.")
flag.Parse()
// Creating A2S Request to Server
client, err := a2s.NewClient(ip + ":" + strconv.FormatUint(uint64(port), 10))
if err != nil {
log.Fatal("Creation of client failed: %w", err)
return
}
defer client.Close()
info, err := client.QueryInfo()
// Checking if we received an error while peforming A2S request
if err != nil {
if strings.HasSuffix(err.Error(), "connection refused") {
log.Fatal("Server refused connection.")
}
log.Fatal("Querying failed: %s", err)
}
log.Printf("Current Server Version: %s", info.Version)
// Creating httpClient and sending Request to Steam API
httpClient := http.Client{}
req, err := http.NewRequest(http.MethodGet, url+info.Version, nil)
if err != nil {
log.Fatal(err)
}
res, err := httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
if res.Body != nil {
defer res.Body.Close()
}
body, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
response := apiResponse{}
err = json.Unmarshal(body, &response)
if err != nil {
log.Fatal(err)
}
// Checking if Server is on the newest Server version, if false execute Command given by the user
if response.Response.UpToDate {
log.Printf("Server is already on newest version.")
} else {
log.Printf("Server needs to be updated, executing command %s", command)
cmd := exec.Command("bash", "-c", command)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
}