#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

clean install binary-arch binary-indep binary:
	dh $@

build:
	install -d baseoa/pak0/vm
	install -d missionpack/mp-pak0/vm
	set -e && \
	cd debian && for c in baseoa/*.contents missionpack/*.contents; do \
		pk3=$${c%.contents}; \
		prefix=$$(basename $${pk3%.pk3}); \
		dir=$${pk3%.pk3}; \
		echo "adding any missing fake QVM files for $$c"; \
		sed -n -e 's/#.*//; /\.qvm$$/p;' < $$c | \
			while read crc filename; do \
				test -f $$prefix-$$crc.qvm || $(MAKE) -C .. -f debian/rules QVMPREFIX=$$prefix QVMCRC=$$crc debian/$$prefix-$$crc.qvm; \
				cp $$prefix-$$crc.qvm ../$$dir/$$filename; \
			done; \
		echo "compressing $$dir to $$pk3"; \
		rm -f ../$$pk3; \
		sed -n -e 's/#.*//; s/.*\t//p;' < $$c | \
			( cd ../$$dir && zip -q -9 ../`basename $$pk3` -@ ); \
		echo "checking contents of $$pk3 against $$c"; \
		( cd .. && perl debian/list-pk3.pl $$pk3 ) | diff -u $$c -; \
	done

DEB_BUILD_GNU_TYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)

debian/$(QVMPREFIX)-$(QVMCRC).qvm: debian/qvmbrute
	./debian/qvmbrute 0x$(QVMCRC) $@ $(QVMPREFIX)

debian/qvmbrute: debian/qvmbrute.c
	$(DEB_BUILD_GNU_TYPE)-gcc -Wall -lz -o debian/qvmbrute debian/qvmbrute.c

import-orig-pk3s:
	@if ! test -f ../baseoa/pak0.pk3; then \
		echo "Put upstream pk3 files in ../baseoa, ../missionpack";\
		exit 1;\
	fi
	install -d debian/baseoa debian/missionpack
	rm -f debian/baseoa/*.contents
	rm -f debian/missionpack/*.contents
	rm -fr baseoa missionpack
	mkdir baseoa missionpack
	# contains paths starting with "../", sigh
	unzip -: ../missionpack/mp-pak0.pk3 ../CREDITS ../COPYING -d missionpack/mp-pak0
	set -e && ( cd .. && ls baseoa/*.pk3 missionpack/*.pk3 ) | \
	while read x; do \
		echo "unpacking $$x"; \
		install -d $${x%.pk3}; \
		perl debian/list-pk3.pl ../$$x > debian/$$x.contents; \
		unzip -q ../$$x -x '*.qvm' '../*' -d $${x%.pk3}; \
	done
