#!/usr/bin/make -f

-include /usr/share/python/python.mk
ifeq (,$(py_sitename))
  py_sitename = site-packages
  py_libdir = /usr/lib/python$(subst python,,$(1))/site-packages
  py_sitename_sh = $(py_sitename)
  py_libdir_sh = $(py_libdir)
endif


PREFIX = debian/python-django
DJANGO_DIR = $(PREFIX)/$(call py_libdir_sh,`pyversions -d`)/django

# FIXME: if the build is run while non-default python version are
# available, the build process will install files in
# /usr/lib/pyshared/pythonX.Y while we don't need them

%:
	dh $@

override_dh_auto_clean:
	rm -rf docs.debian tests/__init__.py
	find -name "*.DS_Store" -delete
	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
	rm -rf docs.debian/_build/html/_sources/

override_dh_auto_test:
	touch tests/__init__.py
	LC_ALL=en_US.utf8 PYTHONPATH=. tests/runtests.py --settings=tests.test_sqlite --verbosity=2

override_dh_install:
	dh_install
	
	# Use default shebang
	perl -pi -e 's|^#!/usr/bin/env python.*|#!/usr/bin/python|' $(DJANGO_DIR)/conf/project_template/manage.py
	chmod +x $(DJANGO_DIR)/conf/project_template/manage.py
	
	# Move scripts to /usr/lib/python-django
	mkdir -p $(PREFIX)/usr/lib/python-django
	mv $(DJANGO_DIR)/bin $(PREFIX)/usr/lib/python-django
	
	# Fix permissions
	chmod 644 $(PREFIX)/etc/bash_completion.d/django_bash_completion
	find $(PREFIX)/usr/lib/python-django/bin/ -name '*.py' -not -name '__init__.py' -print0 | xargs -0r chmod 755
	
	# Rename django-admin.py to django-admin
	mv $(PREFIX)/usr/bin/django-admin.py $(PREFIX)/usr/bin/django-admin
	
	# Remove embedded Javascript libraries
	for FILENAME in jquery.js jquery.min.js; do \
		find $(PREFIX) -name $$FILENAME -exec \
			ln -sf /usr/share/javascript/jquery/$$FILENAME {} \;; \
	done

override_dh_installdocs:
	dh_installdocs
	# Remove embedded copy of libjs-jquery
	cd debian/python-django-doc/usr/share/doc/python-django-doc/html/_static \
		&& rm jquery.js \
		&& ln -s ../../../../javascript/jquery/jquery.js .

override_dh_compress:
	dh_compress -X.js
