package main

import (
    "fmt"
    "net"
    "os"
    "os/exec"
    "strings"
)

func main() {
    hostnames := os.Getenv("HOST_CHECK_HOSTNAMES")
    if hostnames == "" {
        fmt.Println("Error: Environment variable HOST_CHECK_HOSTNAMES not set or empty.")
        return
    }
    hosts := strings.Split(hostnames, ",")

    failOnError := os.Getenv("HOST_CHECK_FAIL_ON_ERROR") == "true"
    hostCheckCommand := os.Getenv("HOST_CHECK_COMMAND")
    errorCommandStr := os.Getenv("HOST_CHECK_ERROR_COMMAND")

    allHostsSuccessful := true

    for _, host := range hosts {
        host = strings.TrimSpace(host)
        fmt.Println("\n---", host, "---")

        ip, err := net.LookupIP(host)
        if err != nil {
            fmt.Println("DNS Resolution Failed:", err)
            allHostsSuccessful = false
            executeCommand(strings.Replace(errorCommandStr, "<hostname>", host, -1)) // Execute error command immediately
            if failOnError {
                os.Exit(1)
            }
            continue
        }
        fmt.Println("Resolved IPs:", ip)

        err = executePing(host)
        if err != nil {
            fmt.Println("Ping Failed:", err)
            allHostsSuccessful = false
            executeCommand(strings.Replace(errorCommandStr, "<hostname>", host, -1)) // Execute error command immediately
            if failOnError {
                os.Exit(1)
            }
            continue
        }

        fmt.Println("Ping Successful")
    }

    if !failOnError && allHostsSuccessful && hostCheckCommand != "" {
        fmt.Println("Executing HOST_CHECK_COMMAND as all hosts were successful.")
        executeCommand(hostCheckCommand)
    }
}

func executeCommand(commandStr string) {
    if commandStr == "" {
        return
    }
    commandStr = strings.Replace(commandStr, "<hostname>", "the host", -1) // Ensure no placeholder remains
    cmdParts := strings.Fields(commandStr)
    cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
    cmdOutput, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Printf("Command Execution Failed: %s, %v\n", commandStr, err)
    } else {
        fmt.Printf("Command Output:\n%s\n", string(cmdOutput))
    }
}

func executePing(host string) error {
    cmd := exec.Command("ping", "-c", "3", host)
    cmdOutput, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Printf("Ping Command Output: %s\n", string(cmdOutput))
        return err
    }
    fmt.Printf("Ping Command Output: %s\n", string(cmdOutput))
    return nil
}

