package main

import (
	"bufio"
	"net"
	"os"
	"strings"
	"time"
)

const (
	defaultTarget = "http://127.0.0.1:8080/health"
	timeout       = 2 * time.Second
)

func main() {
	target := strings.TrimSpace(os.Getenv("HEALTHCHECK_URL"))
	if target == "" {
		target = defaultTarget
	}
	if len(os.Args) > 1 {
		if arg := strings.TrimSpace(os.Args[1]); arg != "" {
			target = arg
		}
	}

	addr, path, ok := splitTarget(target)
	if !ok {
		os.Exit(1)
	}

	conn, err := net.DialTimeout("tcp", addr, timeout)
	if err != nil {
		os.Exit(1)
	}
	defer conn.Close()

	_ = conn.SetDeadline(time.Now().Add(timeout))
	request := "GET " + path + " HTTP/1.1\r\nHost: " + addr + "\r\nConnection: close\r\n\r\n"
	if _, err := conn.Write([]byte(request)); err != nil {
		os.Exit(1)
	}

	line, err := bufio.NewReader(conn).ReadString('\n')
	if err != nil {
		os.Exit(1)
	}

	fields := strings.Fields(line)
	if len(fields) < 2 {
		os.Exit(1)
	}

	code := fields[1]
	if len(code) != 3 || (code[0] != '2' && code[0] != '3') {
		os.Exit(1)
	}
}

func splitTarget(target string) (string, string, bool) {
	target = strings.TrimSpace(target)
	if target == "" || strings.HasPrefix(target, "https://") {
		return "", "", false
	}

	target = strings.TrimPrefix(target, "http://")
	addr := target
	path := "/"
	if slash := strings.IndexByte(target, '/'); slash >= 0 {
		addr = target[:slash]
		path = target[slash:]
	}

	if addr == "" || !strings.Contains(addr, ":") {
		return "", "", false
	}

	return addr, path, true
}
