GO       := $(shell pwd)/deps/go/go/bin/go
GOFLAGS  :=
CGO_LDFLAGS := -L$(shell pwd)/deps/lib -Wl,-rpath,$(shell pwd)/deps/lib
CGO_CFLAGS  := -I$(shell pwd)/deps/include -I$(shell pwd)/deps/whisper.cpp/ggml/include

WHISPER_MODEL := $(shell pwd)/models/stt/ggml-small.bin
PIPER_BIN     := $(shell pwd)/deps/piper/piper
PIPER_MODEL   := $(shell pwd)/models/tts/ru_RU-irina-medium.onnx
PIPER_ESPEAK  := $(shell pwd)/deps/piper/espeak-ng-data

.PHONY: all build build-stt build-tts build-daemon build-client build-web build-poll clean test run-stt run-tts run-web

all: build

build: build-stt build-tts build-daemon build-client build-web build-poll

build-stt:
	CGO_CFLAGS="$(CGO_CFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		$(GO) build $(GOFLAGS) -o mavsttd ./cmd/mavsttd/

build-tts:
	CGO_CFLAGS="$(CGO_CFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		$(GO) build $(GOFLAGS) -o mavttsd ./cmd/mavttsd/

build-daemon:
	CGO_CFLAGS="$(CGO_CFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		$(GO) build $(GOFLAGS) -o mavend ./cmd/mavend/

build-client:
	CGO_CFLAGS="$(CGO_CFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		$(GO) build $(GOFLAGS) -o mavenclient ./cmd/mavenclient/

build-web:
	$(GO) build $(GOFLAGS) -o mavweb ./cmd/mavweb/

build-poll:
	$(GO) build $(GOFLAGS) -o mavpoll ./cmd/mavpoll/

run-web: build-web
	./mavweb -addr :9200 -voice 127.0.0.1:9100

test:
	CGO_CFLAGS="$(CGO_CFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		$(GO) test ./internal/...

run-stt: build-stt
	LD_LIBRARY_PATH="$(shell pwd)/deps/lib" \
		./mavsttd -socket /tmp/maven/stt.sock -model $(WHISPER_MODEL)

run-tts: build-tts
	LD_LIBRARY_PATH="$(shell pwd)/deps/piper" \
		./mavttsd -socket /tmp/maven/tts.sock \
			-piper $(PIPER_BIN) -model $(PIPER_MODEL) -espeak_data $(PIPER_ESPEAK)

deps: deps-whisper deps-piper

deps-whisper:
	cd deps/whisper.cpp && cmake -B build -DCMAKE_BUILD_TYPE=Release \
		-DWHISPER_BUILD_TESTS=OFF -DWHISPER_BUILD_SERVER=OFF && \
		cmake --build build --config Release -j$$(nproc)
	cp deps/whisper.cpp/build/bin/libwhisper.so* deps/lib/
	cp deps/whisper.cpp/build/bin/libggml*.so* deps/lib/
	cp deps/whisper.cpp/build/bin/libparakeet.so* deps/lib/

deps-piper:
	mkdir -p deps/
	curl -sL "https://github.com/rhasspy/piper/releases/download/2023.11.14-2/piper_linux_x86_64.tar.gz" \
		-o /tmp/piper.tar.gz
	tar -xzf /tmp/piper.tar.gz -C deps/

clean:
	rm -f mavend mavenclient mavsttd mavttsd mavweb mavpoll
