#!/usr/bin/make -f

# We require some bash features
override SHELL := /bin/bash

include /usr/share/dpkg/default.mk

LANGUAGES := en $(patsubst debian/po/%.po,%,$(wildcard debian/po/*.po))

# Distributed files that we regenerate
AUTOGEN_FILES := HACKING Makefile.am Makefile.cyg Makefile.emcc \
		 Makefile.gnustep Makefile.gtk Makefile.in Makefile.nestedvm \
		 Makefile.osx Makefile.vc Makefile.wce aclocal.m4 configure \
		 depcomp install-sh list.c missing preprocessed.but \
		 puzzles.cnt puzzles.hlp puzzles.txt

CFLAGS += -Wno-error=deprecated-declarations
ifeq ($(DEB_HOST_ARCH), ppc64el)
CFLAGS := $(filter-out -O3,$(CFLAGS)) -O2
endif

%:
	dh $@

override_dh_auto_configure:
	./mkfiles.pl
	./mkauto.sh
	CFLAGS="$(CFLAGS)" CPPFLAGS="$(CPPFLAGS) -DDEBIAN_VERSION=\"\\\"$(DEB_VERSION)\\\"\"" LDFLAGS="$(LDFLAGS)" ./configure --prefix=/usr --bindir=/usr/games --program-prefix=sgt-
	[ -L po ] || ln -s debian/po po
	rm -f preprocessed.but

override_dh_auto_build:
	$(MAKE)
	$(MAKE) -f Makefile.doc BINPREFIX=sgt-

# Disable running tests; upstream tarballs don't include the necessary files
override_dh_auto_test:

override_dh_auto_install:
	$(MAKE) DESTDIR=debian/sgt-puzzles install

override_dh_installdocs:
	for lang in $(LANGUAGES); do \
		dh_install doc/html-$$lang/*.html usr/share/sgt-puzzles/help/$$lang \
		|| exit; \
	done
	dh_installdocs

override_dh_installman:
	for lang in $(LANGUAGES); do \
		dh_installman --language=$${lang/en/C} doc/man-$$lang/* || exit; \
	done

override_dh_install:
	dh_install debian/desktop/*.desktop usr/share/applications
	for icon in icons/*-48d24.png; do \
	    base="$$(basename $$icon -48d24.png)" && \
	    install -m644 $$icon debian/sgt-puzzles/usr/share/icons/hicolor/48x48/apps/sgt-$$base.png \
	    || exit; \
	done

override_dh_auto_clean:
	! [ -f Makefile ] || $(MAKE) distclean
	$(MAKE) -f Makefile.doc clean
	if [ -d .git ]; then				\
		git checkout HEAD $(AUTOGEN_FILES);	\
	else						\
		rm -f $(AUTOGEN_FILES);			\
	fi
	rm -f po
	dh_clean debian/sgt-puzzles.menu debian/substvars compile gamedesc.txt version2.def

get-orig-source:
	wget -O puzzles-new.tar.gz https://www.chiark.greenend.org.uk/~sgtatham/puzzles/puzzles.tar.gz
	version="$$(tar -xOzf puzzles-new.tar.gz --wildcards '*/version.h' | \
		    sed -n 's/^\#define VER "Version \([^ ]*\)"$$/\1/p')" \
	&& test -n "$$version"						\
	&& mv puzzles-new.tar.gz ../"sgt-puzzles_$$version.orig.tar.gz"
