# latstat 1.0.0
CC      ?= cc
CFLAGS  ?= -O2 -Wall -Wextra -std=c99
PREFIX  ?= /usr/local

BIN      = latstat
BIN_STAT = latstat-static
SRC      = latstat.c

all: $(BIN)

$(BIN): $(SRC)
	$(CC) $(CFLAGS) -o $@ $(SRC) -lm

# Fully static build: runs on any x86_64 Linux, no glibc version coupling.
# Hostname resolution inside a static glibc binary needs the target system's
# NSS modules; numeric addresses always work.
static: $(SRC)
	$(CC) $(CFLAGS) -static -o $(BIN_STAT) $(SRC) -lm

# Binaries as shipped in bin/: stripped, still ABI-identical to `make` output.
release: all static
	strip -s $(BIN) $(BIN_STAT)

install: $(BIN)
	install -D -m 0755 $(BIN) $(DESTDIR)$(PREFIX)/bin/$(BIN)

# Loopback smoke test: a real listener must answer, a closed port must fail
# with exit 2, and an unresolvable name must fail with exit 1.
check: $(BIN)
	@python3 -c 'import socket,time; s=socket.socket(); s.bind(("127.0.0.1",9)); s.listen(8); time.sleep(3)' & \
	 sleep 1; ./$(BIN) -c 3 -q -H 127.0.0.1:9 >/dev/null && echo "listener: PASS"
	@./$(BIN) -c 2 -q -t 300 127.0.0.1:1 >/dev/null; test $$? -eq 2 && echo "closed port: PASS"
	@./$(BIN) -c 1 -q no-such-host.invalid >/dev/null 2>&1; test $$? -eq 1 && echo "bad host: PASS"

clean:
	rm -f $(BIN) $(BIN_STAT)

.PHONY: all static release install check clean
