#!/usr/bin/make -f

libx264N := $(shell sed -rn 's/^Package:[[:space:]]*(libx264-[0-9]+)[[:space:]]*$$/\1/p' debian/control)

DEB_HOST_MULTIARCH  ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_HOST_GNU_CPU    ?= $(shell dpkg-architecture -qDEB_HOST_GNU_CPU)

include debian/confflags

LDFLAGS += -Wl,--as-needed

DH_INSTALL_INPUT_FILES = debian/libx264-118.install.in \
                         debian/libx264-dev.install.in

DH_INSTALL_OUTPUT_FILES = $(DH_INSTALL_INPUT_FILES:.in=)

%:
	dh $@ --parallel

$(DH_INSTALL_OUTPUT_FILES): $(DH_INSTALL_INPUT_FILES)
	@echo "Generating $$(echo $@ | sed 's/\.in$$//') from $@"
	sed -e 's/@DEB_HOST_MULTIARCH@/$(DEB_HOST_MULTIARCH)/g' $@.in > $@

override_dh_auto_build:
	debian/rules $(DH_INSTALL_OUTPUT_FILES)
	# Build static lib
	LDFLAGS="$(LDFLAGS)" ./configure $(static_confflags) \
	   || ( tail -v -n +0 config.log config.log ; exit 1 )
	$(MAKE)
	$(MAKE) install DESTDIR=$(CURDIR)/debian/install/static
	$(MAKE) distclean
	# Build shared lib
	CFLAGS="$(shared_extra_cflags)" LDFLAGS="$(LDFLAGS)" ./configure $(shared_confflags) \
	   || ( tail -v -n +0 config.log config.log ; exit 1 )
	$(MAKE)
	$(MAKE) install DESTDIR=$(CURDIR)/debian/install/shared
ifeq ($(do_opt),yes)
	$(MAKE) distclean
	# Build opt lib
	LDFLAGS="$(LDFLAGS)" ./configure $(opt_confflags) \
	   || ( tail -v -n +0 config.log config.log ; exit 1 )
	$(MAKE)
	$(MAKE) install DESTDIR=$(CURDIR)/debian/install/opt
endif

override_dh_auto_configure:
	# dh_auto_configure phase handled via dh_auto_build.

override_dh_auto_install:
	# dh_auto_install phase handled via dh_auto_build.

override_dh_auto_clean:
	rm -rf debian/install
	$(MAKE) -o config.mak distclean
	dh_clean config.mak2 $(DH_INSTALL_OUTPUT_FILES)

override_dh_install:
	dh_install --list-missing --sourcedir=debian/install
ifeq ($(do_opt),yes)
	mkdir -p debian/$(libx264N)$(opt_libdir)
	cp -a debian/install/opt$(opt_libdir)/*.so.* debian/$(libx264N)$(opt_libdir)
endif

override_dh_installman:
	test -f debian/x264.1 || debian/rules debian/x264.1
	dh_installman

debian/x264.1: debian/install/static/usr/bin/x264
	help2man -n"fast h264 encoder" -N -s1 -S "Videolan project" -h '--fullhelp' \
		debian/install/static/usr/bin/x264 > debian/x264.1

debian/install/static/usr/bin/x264:
	debian/rules build
