VERSION ?= 0.1.0
COMMIT  ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
DATE    ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
LDFLAGS := -s -w -X prx/internal/version.Version=$(VERSION) -X prx/internal/version.Commit=$(COMMIT) -X prx/internal/version.Date=$(DATE)
PREFIX  ?= /usr
BINDIR  ?= $(PREFIX)/bin
LIBDIR  ?= $(PREFIX)/lib/prx
MANDIR  ?= $(PREFIX)/share/man

.PHONY: all build test vet fmt lint clean install uninstall integration man

all: build

build:
	CGO_ENABLED=0 go build -buildvcs=false -trimpath -ldflags "$(LDFLAGS)" -o bin/prx ./cmd/prx
	CGO_ENABLED=0 go build -buildvcs=false -trimpath -ldflags "$(LDFLAGS)" -o bin/prx-helper ./cmd/prx-helper

test:
	go test ./...

vet:
	go vet ./...

fmt:
	gofmt -w .

lint: vet
	gofmt -l . | tee /dev/stderr | wc -l | grep -q '^0$$'

integration: build
	PRX_BIN=$(CURDIR)/bin/prx sudo -E ./scripts/integration-test.sh

install: build
	install -Dm755 bin/prx $(DESTDIR)$(BINDIR)/prx
	install -Dm755 bin/prx-helper $(DESTDIR)$(LIBDIR)/prx-helper
	install -Dm644 polkit/org.prx.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/org.prx.policy
	install -Dm644 systemd/prx-reapply.service $(DESTDIR)$(PREFIX)/lib/systemd/system/prx-reapply.service
	install -Dm644 systemd/prx-reapply.timer $(DESTDIR)$(PREFIX)/lib/systemd/system/prx-reapply.timer
	install -Dm644 man/prx.1 $(DESTDIR)$(MANDIR)/man1/prx.1
	install -Dm644 man/prx-helper.1 $(DESTDIR)$(MANDIR)/man1/prx-helper.1

# Validate the man pages with groff (no-op if groff is unavailable).
man:
	@command -v groff >/dev/null 2>&1 && groff -man -Tutf8 -z man/prx.1 man/prx-helper.1 && echo "man: ok" || echo "man: groff not installed, skipped"

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/prx
	rm -f $(DESTDIR)$(LIBDIR)/prx-helper
	rm -f $(DESTDIR)$(PREFIX)/share/polkit-1/actions/org.prx.policy
	rm -f $(DESTDIR)$(PREFIX)/lib/systemd/system/prx-reapply.service
	rm -f $(DESTDIR)$(PREFIX)/lib/systemd/system/prx-reapply.timer
	rm -f $(DESTDIR)$(MANDIR)/man1/prx.1
	rm -f $(DESTDIR)$(MANDIR)/man1/prx-helper.1

clean:
	rm -rf bin
