#!/usr/bin/make -f

export PYBUILD_NAME=django

PREFIX = debian/python-django
PREFIX3 = debian/python3-django
PREFIXC = debian/python-django-common

%:
	dh $@ --with sphinxdoc,python2,python3 --buildsystem=pybuild

override_dh_auto_clean:
	rm -rf docs.debian tests/__init__.py
	find -name "*.DS_Store" -delete
	chmod a-x django/contrib/gis/tests/data/texas.dbf
	dh_auto_clean

override_dh_auto_build:
	dh_auto_build
	
	# Build the HTML documentation.
	# We programmatically replace most instances of django-admin.py with
	# django-admin and remove the source files from the target _build.
	cp -r docs docs.debian
	find docs.debian -type f -print0 | xargs -0r perl -pi -e 's|(?<!/)(django-admin)\.py|$$1|'
	make -C docs.debian html

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	touch tests/__init__.py
	mkdir -p tmp-locales
	localedef -i /usr/share/i18n/locales/en_US -c -f UTF-8 -A /usr/share/locale/locale.alias tmp-locales/en_US.UTF-8
	LOCPATH=$(CURDIR)/tmp-locales LC_ALL=en_US.UTF-8 PYTHONPATH=. tests/runtests.py --settings=tests.test_sqlite --verbosity=2
	rm -rf tmp-locales
endif

override_dh_clean:
	# backup~ is used in tests
	dh_clean -Xbackup~

override_dh_install:
	dh_install
	
	# Fix permissions
	chmod 644 $(PREFIXC)/etc/bash_completion.d/django_bash_completion
	chmod 755 $(PREFIXC)/usr/bin/django-admin
	
	# Rename django-admin.py to django-admin
	rm $(PREFIX)/usr/bin/django-admin.py
	rm $(PREFIX3)/usr/bin/django-admin.py
	
	# Remove embedded Javascript libraries
	set -e; for FILENAME in jquery.js jquery.min.js; do \
		find $(PREFIX) -name $$FILENAME -exec \
			ln -sf /usr/share/javascript/jquery/$$FILENAME {} \;; \
		find $(PREFIX3) -name $$FILENAME -exec \
			ln -sf /usr/share/javascript/jquery/$$FILENAME {} \;; \
	done

override_dh_python3:
	dh_python3
	find debian/python3-django/usr/lib/python3/dist-packages/ -type f -not -name '*.py' | \
	(while read file; do \
		relname=$${file##debian/python3-django/usr/lib/python3/dist-packages/}; \
		reldirname=$$(dirname $$relname); \
		mkdir -p debian/python-django-common/usr/share/python-django-common/$$reldirname; \
		mv $$file debian/python-django-common/usr/share/python-django-common/$$reldirname/; \
		ln -sf /usr/share/python-django-common/$$relname $$file; \
		if test -e debian/python-django/usr/share/pyshared/$$relname; then \
		    rm debian/python-django/usr/share/pyshared/$$relname; \
		    ln -sf /usr/share/python-django-common/$$relname debian/python-django/usr/share/pyshared/$$relname; \
		else \
		    rm debian/python-django/usr/lib/python2.7/dist-packages/$$relname; \
		    ln -sf /usr/share/python-django-common/$$relname debian/python-django/usr/lib/python2.7/dist-packages/$$relname; \
		fi \
	done)

override_dh_compress:
	dh_compress -X.js -Xobjects.inv
