SHELL := /usr/bin/env bash

.PHONY: help
help:
	@echo "make build       — build server + frontend locally (sanity check)"
	@echo "make check       — type-check + go vet"
	@echo "make audio-pull  — copy source WAVs from Dropbox into content/audio/"
	@echo "make audio       — transcode each side WAV → Opus"
	@echo "make images      — convert content/images/*.jpg → WebP"
	@echo "make artists     — regenerate artists.json from audio.yaml"
	@echo "make content     — artists + images + audio"
	@echo "make deploy-assets — rsync web/static/{audio,images}/ to sprade for production"
	@echo "make tag V=patch|minor|major   — bump version tag and push"
	@echo "make prefetch    — print sha256 + npmDepsHash + vendorHash for the homelab module"

.PHONY: audio-pull
audio-pull:
	bin/pull-audio

.PHONY: audio
audio:
	bin/build-audio

.PHONY: images
images:
	bin/build-images

.PHONY: artists
artists:
	bin/build-artists

.PHONY: content
content: artists images audio

.PHONY: deploy-assets
deploy-assets:
	@if [ ! -d web/static/audio ] || [ -z "$$(ls web/static/audio 2>/dev/null)" ]; then \
		echo "error: web/static/audio is empty. Run \`make audio\` first." >&2; exit 1; \
	fi
	@if [ ! -d web/static/images ] || [ -z "$$(ls web/static/images 2>/dev/null)" ]; then \
		echo "error: web/static/images is empty. Run \`make images\` first." >&2; exit 1; \
	fi
	rsync -av --delete --progress web/static/audio/ deploy@sprade:/var/lib/docent/audio/
	rsync -av --delete --progress web/static/images/ deploy@sprade:/var/lib/docent/images/

.PHONY: build
build:
	cd web    && npm install && npm run build
	cd server && go build -o docent ./...

.PHONY: check
check:
	cd web    && npm run check
	cd server && go vet ./...

.PHONY: tag
tag:
	@if [ -z "$(V)" ]; then echo "usage: make tag V=patch|minor|major" >&2; exit 1; fi
	@latest=$$(git describe --tags --abbrev=0 2>/dev/null | sed 's/^v//' || echo "0.0.0"); \
	IFS=. read -r maj min pat <<< "$$latest"; \
	case "$(V)" in \
		major) maj=$$((maj+1)); min=0; pat=0 ;; \
		minor) min=$$((min+1)); pat=0 ;; \
		patch) pat=$$((pat+1)) ;; \
		*) echo "V must be patch|minor|major" >&2; exit 1 ;; \
	esac; \
	new="v$${maj}.$${min}.$${pat}"; \
	echo "tagging $$new"; \
	git tag -a "$$new" -m "$$new"; \
	git push --tags

.PHONY: prefetch
prefetch:
	@latest=$$(git describe --tags --abbrev=0); \
	url=$$(git remote get-url origin); \
	echo "rev = $$latest"; \
	echo "src hash:"; \
	nix-prefetch-git "$$url" --rev "$$latest" --quiet | sed -n 's/.*"sha256": "\(.*\)".*/  \1/p'; \
	echo ""; \
	echo "Run \`nix build .#docent-frontend\` and \`nix build .#docent-server\` once to populate"; \
	echo "npmDepsHash and vendorHash respectively (will fail on mismatch and print correct hash)."
