#!/usr/bin/make -f

export APPNAME=mineclonia
export TARBALLNAME=mineclonia-game-mineclonia
export APPVERSION=$(shell git tag | sort -V | tail -n1 )

%:
	dh $@

override_dh_auto_clean:
	dh_auto_clean
	git restore -- mods tools 2>/dev/null || :

override_dh_auto_install:
	dh_auto_install
	pwd ; ls -alR debian ;
	set -e -x ; cd $(CURDIR)/mods ; \
	set -e -x ; fdupes -r -1 -o name . | while read lines ; do \
		unset MAIN ; \
		for dupes in $$lines ; do \
			if [ -z "$$MAIN" ] ; then \
				MAIN=$$dupes ; \
			else \
				THISDIR=`dirname $$dupes` ; \
				LINKDEST=`realpath --relative-to=$$THISDIR $$MAIN` ; \
				ln -sf $$LINKDEST $$dupes ; \
			fi ; \
		done ; \
	done

.PHONY: update_build_depends update_dsc update_obs update
update_obs:
	@echo "Updating _service file for OBS. Use with: debuild -- update_obs"
	cd ~/dev/mineclonia || { cd ~/dev ; git clone $$( awk '/Homepage/{print $$NF}' mineclonia ) ; } ;\
	git pull || : ; \
	url="$$( git remote -v | awk 'NR==1{print $$2}' | sed -r -e 's@/@\\/@g;' )" ; \
	version="$$( git tag | sort -V | tail -n1 )" ; \
	echo version is $${version} and url=$${url} ; \
	git checkout $${version} ; \
	cd $(CURDIR) ; sed -i -r -e "/url.*$${url}/{n;s@(\"revision\">).*(</param)@\1$${version}\2@" -e "}" debian/_service

update_dsc:
	@echo "Updating dsc file for OBS. Manually update changelog first, then run: debuild -- update_dsc"
	version_release="$$( awk 'NR==1{gsub(/[\(\)]/,"",$$2);print $$2}' debian/changelog )" ; \
	echo version_release is $${version_release} ; \
	sed -i -r -e "/^Version:/{s/.*/Version: $${version_release}/" -e "}" debian/*dsc

# vibecoded with duck.ai
update_build_depends:
	@echo "Updating build_depends for dsc file."
	build_depends="$$( awk ' \
		BEGIN { inbd=0 } \
		/^Build-Depends:/ { inbd=1; sub(/^Build-Depends:[[:space:]]*/, "", $$0); print; next } \
		inbd && /^[[:space:]]*#/ { next } \
		inbd && /^[[:space:]]/ { sub(/^[[:space:]]+/, "", $$0); print; next } \
		inbd && /^[^[:space:]]+[^:]*:/ { inbd=0 } \
	' debian/control | tr '\n' ' ' | sed -r -e 's/, ?$$/\n/' )" ; \
	echo build_depends=$${build_depends} ; \
	sed -i.bak -r -e "/^Build-Depends:/{s/.*/Build-Depends:$${build_depends}/}" debian/*dsc

update: update_obs update_dsc update_build_depends
	@echo "Updated obs, dsc, and build_depends"

tarball:
	cd $(CURDIR)/.. ; rm -f ${TARBALLNAME}_${APPVERSION}.orig.tar.gz && \
		tar -zcf ${TARBALLNAME}_${APPVERSION}.orig.tar.gz --exclude 'debian' --exclude '.git' ${APPNAME}
