GO ?= go
NPM ?= npm

VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null)
LDFLAGS := -s -w \
	-X github.com/apernet/OpenGFW/cmd.appVersion=$(VERSION) \
	-X github.com/apernet/OpenGFW/cmd.appCommit=$(COMMIT)

FRONTEND := web/frontend

.PHONY: all
all: web build

## build: build the OpenGFW binary (embeds the web UI in web/dist)
.PHONY: build
build:
	$(GO) build -o OpenGFW -ldflags "$(LDFLAGS)" .

## web: build the web UI into web/dist
.PHONY: web
web:
	cd $(FRONTEND) && $(NPM) install && $(NPM) run build

## web-dev: run the Vite dev server against a local OpenGFW instance
.PHONY: web-dev
web-dev:
	cd $(FRONTEND) && $(NPM) run dev

## devserver: serve the web UI with synthetic data (works on any OS)
.PHONY: devserver
devserver:
	$(GO) run ./web/devserver

.PHONY: test
test:
	$(GO) test ./...

.PHONY: vet
vet:
	$(GO) vet ./...

.PHONY: clean
clean:
	rm -f OpenGFW
	rm -rf $(FRONTEND)/node_modules

.PHONY: install
install: build
	@echo "Installing OpenGFW to /usr/local/bin"
	@install -m 755 OpenGFW /usr/local/bin/OpenGFW || (echo "install failed: try running as root or use sudo" && exit 1)
	@echo "Installing systemd unit to /etc/systemd/system/opengfw.service"
	@printf '%s\n' \
		'[Unit]' \
		'Description=OpenGFW' \
		'After=network.target' \
		'' \
		'[Service]' \
		'ExecStart=/usr/local/bin/OpenGFW -c /etc/opengfw/config.yaml /etc/opengfw/rules.yaml' \
		'Restart=on-failure' \
		'User=root' \
		'Group=root' \
		'WorkingDirectory=/etc/opengfw' \
		'' \
		'[Install]' \
		'WantedBy=multi-user.target' \
	> /tmp/opengfw.service || (echo "write failed: try running as root or use sudo" && exit 1)

	@echo "Installing default config to /etc/opengfw/"
	@mkdir -p /etc/opengfw || (echo "mkdir failed: try running as root or use sudo" && exit 1)
	@install -m 644 config.yaml /etc/opengfw/config.yaml || (echo "copy config failed: try running as root or use sudo" && exit 1)
	@install -m 644 rules.yaml /etc/opengfw/rules.yaml || (echo "copy rules failed: try running as root or use sudo" && exit 1)
	@mv /tmp/opengfw.service /etc/systemd/system/opengfw.service || (echo "move failed: try running as root or use sudo" && exit 1)
	@echo "Reloading systemd daemon and enabling service"
	@systemctl daemon-reload || (echo "daemon-reload failed: ensure systemd is available" && exit 1)
	@systemctl enable --now opengfw.service || (echo "enabling service failed: try running as root or use sudo" && exit 1)
