#!/usr/bin/make -f

#include /usr/share/dpatch/dpatch.make

top_dir      := $(shell pwd)
build_dir    := $(top_dir)/build-tree

include /usr/share/cdbs/1/rules/debhelper.mk
include /usr/share/cdbs/1/rules/simple-patchsys.mk

DEB_TAR_SRCDIR := r5u870_src

include /usr/share/cdbs/1/rules/tarball.mk

DEB_DH_INSTALL_ARGS += --autodest
DEB_DH_INSTALL_SOURCEDIR=${top_dir}/debian/tmp
FWDIR="${DEB_DH_INSTALL_SOURCEDIR}/lib/firmware"
RICOH_DMKS_SRC_DIR = ${DEB_DH_INSTALL_SOURCEDIR}/usr/src/r5u870-$(DEB_UPSTREAM_VERSION)

pre-build::
	dh_testdir
	# Rename the source directory
	if test -d "$(build_dir)/r5u870"; then \
		rm -rf "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
		mv -v "$(build_dir)/r5u870" "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
	fi
	if test -d "$(build_dir)/r5u870-$(DEB_UPSTREAM_VERSION)"; then \
		rm -rf "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
		mv -v "$(build_dir)/r5u870-$(DEB_UPSTREAM_VERSION)" "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
	fi
	if test -d "$(build_dir)/r5u870_patched"; then \
		rm -rf "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
		mv -v "$(build_dir)/r5u870_patched" "$(build_dir)/$(DEB_TAR_SRCDIR)"; \
	fi;
	# Need to be executable for DKMS
	chmod +x ./debian/do_Module.symvers;
	# Create directories
	install -d -m 755 "${FWDIR}"
	install -d -m 755 "${RICOH_DMKS_SRC_DIR}"
	# Copy firmwares
	cp -f "$(build_dir)/$(DEB_TAR_SRCDIR)/"*.fw "${DEB_DH_INSTALL_SOURCEDIR}/lib/firmware"
	# Copy source files for DKMS
	cp -Rf "$(build_dir)/$(DEB_TAR_SRCDIR)/"* "${RICOH_DMKS_SRC_DIR}"
	rm -f "${RICOH_DMKS_SRC_DIR}/"*.fw
	rm -f "${RICOH_DMKS_SRC_DIR}/recode-fw.scm"
	rm -f "${RICOH_DMKS_SRC_DIR}/ChangeLog"
	rm -f "${RICOH_DMKS_SRC_DIR}/AUTHORS"
	rm -f "${RICOH_DMKS_SRC_DIR}/COPYING"
	rm -f "${RICOH_DMKS_SRC_DIR}/MAINTAINERS"
	rm -f "${RICOH_DMKS_SRC_DIR}/NEWS"
	rm -f "${RICOH_DMKS_SRC_DIR}/README"
	# Create DKMS'ified control files
	sed -e 's/CVERSION/$(DEB_UPSTREAM_VERSION)/g' < debian/ricoh-webcam-r5u870.dirs.in > debian/ricoh-webcam-r5u870.dirs
	sed -e 's/CVERSION/$(DEB_UPSTREAM_VERSION)/g' < debian/ricoh-webcam-r5u870.install.in > debian/ricoh-webcam-r5u870.install
	# Create DKMS control files
	sed -e 's/CVERSION/$(DEB_UPSTREAM_VERSION)/g' < debian/ricoh-webcam-r5u870.dkms.conf.in > "${RICOH_DMKS_SRC_DIR}/dkms.conf"

clean::
	dh_testdir
	dh_testroot
	rm -f *.cdbs-config_list
	rm -f debian/ricoh-webcam-r5u870.dirs
	rm -f debian/ricoh-webcam-r5u870.install
	rm -rf "$(build_dir)"
	dh_clean

install: build
	dh_testdir
	dh_testroot
	dh_installdirs
	dh_install --autodest "--sourcedir=${DEB_DH_INSTALL_SOURCEDIR}"
	dh_link
	dh_installman
	dh_installdocs

