VER ?= v4
APP_DIR_v3 := Avida-ED
APP_DIR_v4 := Avida-ED-Eco
APP_DIR := $(APP_DIR_$(VER))
DEFAULT_PATH := /$(APP_DIR)/index.html

.PHONY: fetch-v3 fetch-v4 fetch-v3-url fetch-v4-url check-ver check-assets check-linux-deps inject-$(VER) build-linux build-mac build-win appimage winexe macapp all

fetch-v3:
	MODE=github ED_VER=v3 OUTDIR=apps/v3 bash tools/fetch_assets.sh
fetch-v4:
	MODE=github ED_VER=v4 OUTDIR=apps/v4 bash tools/fetch_assets.sh
fetch-v3-url:
	MODE=url ED_VER=v3 URL=https://avida-ed.msu.edu/app/ OUTDIR=apps/v3 bash tools/fetch_assets.sh
fetch-v4-url:
	MODE=url ED_VER=v4 URL=https://avida-ed.github.io/Avida-ED-Eco/ OUTDIR=apps/v4 bash tools/fetch_assets.sh

check-ver:
	@test -n "$(APP_DIR)" || { echo "Unsupported VER=$(VER). Use VER=v3 or VER=v4."; exit 2; }

check-assets: check-ver
	@test -f "apps/$(VER)/$(APP_DIR)/index.html" || { echo "Missing apps/$(VER)/$(APP_DIR)/index.html. Run make fetch-$(VER) first."; exit 2; }

check-linux-deps:
	@command -v cargo >/dev/null || { echo "Missing cargo. Install Rust 1.75+ with rustup."; exit 127; }
	@command -v pkg-config >/dev/null || { echo "Missing pkg-config. Install pkg-config plus GTK/WebKitGTK development packages."; exit 127; }
	@pkg-config --exists glib-2.0 gtk+-3.0 || { echo "Missing GLib/GTK development packages visible to pkg-config."; exit 127; }
	@pkg-config --exists webkit2gtk-4.1 || pkg-config --exists webkit2gtk-4.0 || { echo "Missing WebKitGTK development package visible to pkg-config."; exit 127; }

inject-$(VER): check-assets
	bash tools/inject_webroot.sh $(VER)

# Build binaries natively on each OS runner
build-linux: check-ver check-linux-deps inject-$(VER)
	cd server-ui && AVIDA_ED_DEFAULT_PATH="$(DEFAULT_PATH)" cargo build --release

build-mac: inject-$(VER)
	cd server-ui && AVIDA_ED_DEFAULT_PATH="$(DEFAULT_PATH)" cargo build --release

build-win: inject-$(VER)
	cd server-ui && AVIDA_ED_DEFAULT_PATH="$(DEFAULT_PATH)" cargo build --release

# Package
appimage: build-linux
	bash packaging/linux/make_appimage.sh $(VER) server-ui/target/release/avidaed_onefile

winexe: build-win
	# Example: pass location of WebView2 Fixed runtime and built exe
	powershell -ExecutionPolicy Bypass -File packaging/windows/make_windows_sfx.ps1 \
	  -Version $(VER) \
	  -BinPath $(CURDIR)/server-ui/target/release/avidaed_onefile.exe \
	  -WV2Fixed "C:\SDKs\WebView2.FixedRuntime" \
	  -OutputDir $(CURDIR)

macapp: build-mac
	bash packaging/mac/make_macos_bundle.sh $(VER) server-ui/target/release/avidaed_onefile $(CURDIR)

all:
	@echo "Targets:"
	@echo "  make fetch-v3 | fetch-v4"
	@echo "  make build-linux | build-mac | build-win"
	@echo "  make appimage | winexe | macapp"
