APP := jukebox
APP_PKG := ./cmd/jukebox
APP_URL := http://127.0.0.1:8080

ROOT_DIR := $(CURDIR)
DEV_DIR := $(ROOT_DIR)/.tmp
CONFIG_DIR := $(DEV_DIR)/config
MEDIA_DIR := $(DEV_DIR)/media
MOUNT_DIR := $(DEV_DIR)/mount
CONFIG_PATH := $(CONFIG_DIR)/config.json
GOCACHE_DIR := $(DEV_DIR)/gocache

.PHONY: run test build release dev-dirs

dev-dirs:
	mkdir -p "$(CONFIG_DIR)" "$(MEDIA_DIR)" "$(MOUNT_DIR)" "$(GOCACHE_DIR)"

run: dev-dirs
	@sh -c '\
		url="$(APP_URL)"; \
		open_url() { \
			if command -v open >/dev/null 2>&1; then \
				open "$$1"; \
			elif command -v powershell >/dev/null 2>&1; then \
				powershell -NoProfile -Command "Start-Process '\''$$1'\''" >/dev/null; \
			elif command -v xdg-open >/dev/null 2>&1; then \
				xdg-open "$$1" >/dev/null 2>&1; \
			fi; \
		}; \
		for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do \
			if curl -fsS "$$url/health" >/dev/null 2>&1; then \
				open_url "$$url"; \
				exit 0; \
			fi; \
			sleep 1; \
		done \
	' &
	GOCACHE="$(GOCACHE_DIR)" go run $(APP_PKG) \
		-config "$(CONFIG_PATH)" \
		-media "$(MEDIA_DIR)" \
		-mount "$(MOUNT_DIR)" \
		-addr ":8080"

test: dev-dirs
	GOCACHE="$(GOCACHE_DIR)" go test ./...

build: dev-dirs
	GOCACHE="$(GOCACHE_DIR)" go build -o "$(ROOT_DIR)/$(APP)" $(APP_PKG)

release:
	./ops/build-release.sh
