#!/usr/bin/make -f

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

# This has to be exported to make some magic below work.
export DH_OPTIONS

include /usr/share/dpatch/dpatch.make

DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)

NCPUS := $(shell getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)

ifeq ($(NCPUS),-1)
	NCPUS:=1
endif

ifeq ($(NCPUS),0)
	NCPUS:=1
endif

confflags = --enable-pthread --prefix=/usr --enable-debug 

CFLAGS = -Wall -g

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
	CFLAGS += -O0
else
	CFLAGS += -O2
endif

build: build-stamp
build-stamp: patch-stamp
	dh_testdir

	# Build static lib

#	$(MAKE) clean
	CFLAGS="$(CFLAGS)" ./configure $(confflags)
	$(MAKE) -j $(NCPUS) libx264.a

	# Backup static lib
	mv libx264.a libx264.a.bak

	# Build shared lib + GTK frontend
	$(MAKE) clean

	CFLAGS="$(CFLAGS)" ./configure $(confflags) --enable-shared \
	--enable-pic --enable-gtk --enable-visualize --enable-mp4-output

	$(MAKE) -j $(NCPUS)

	# Restore static lib
	mv libx264.a.bak libx264.a
	touch $@

clean:
	dh_testdir
	dh_testroot
	rm -f build-stamp

	-$(MAKE) distclean

	rm -f libx264.a.bak

	debian/rules unpatch

	rm -rf .pc

	dh_clean

install:
	dh_testdir
	dh_testroot
	dh_clean -k
	dh_installdirs

	$(MAKE) install DESTDIR=$(CURDIR)/debian/tmp

	dh_install --fail-missing --sourcedir=debian/tmp -Xx264gtk -Xx264_gtk

	cp gtk/x264_gtk_encode debian/x264/usr/bin

binary-common:
	dh_testdir
	dh_testroot
	dh_installchangelogs ChangeLog
	dh_installdocs
	dh_installexamples
	dh_installman debian/x264.1
	dh_link
	dh_strip
	dh_compress 
	dh_fixperms
	dh_makeshlibs -V
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary-indep: build install

binary-arch: build install
	$(MAKE) -f debian/rules DH_OPTIONS=-s binary-common

binary: binary-arch binary-indep
.PHONY: build clean binary-indep binary-arch binary install
