#!/usr/bin/make -f
export DH_OPTIONS

DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_CPU ?= $(shell dpkg-architecture -qDEB_HOST_GNU_CPU)
DEB_HOST_ARCH_CPU ?= $(shell dpkg-architecture -qDEB_HOST_GNU_CPU)
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

# Calculating musl based architecture
MUSL_ARCH=$(DEB_HOST_GNU_CPU)
MUSL_TRIPLE=$(DEB_HOST_GNU_CPU)-linux-musl

ifneq (,$(findstring armel,$(DEB_HOST_ARCH)))
  MUSL_ARCH=arm
  MUSL_TRIPLE=arm-linux-musleabi
endif

ifneq (,$(findstring armhf,$(DEB_HOST_ARCH)))
  MUSL_ARCH=armhf
  MUSL_TRIPLE=arm-linux-musleabihf
endif

ifeq ($(DEB_HOST_ARCH_CPU),i386)
  MUSL_ARCH=i386
  MUSL_TRIPLE=i386-linux-musl
endif
export MUSL_ARCH
export MUSL_TRIPLE

# Cross build support
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))  
  CC ?= cc
else
  CC=$(DEB_HOST_GNU_TYPE)-gcc
  CROSS_COMPILE=$(DEB_HOST_GNU_TYPE)-
  export CROSS_COMPILE
endif
export CC

# Clear variables to make musl happy
CFLAGS=
CPPFLAGS=
LDFLAGS=
export CFLAGS
export CPPFLAGS
export LDFLAGS

# Substitue control file variables debending on the debian libc type
# If musl is the native libc, we can provide libc and depend on linux-libc-dev
ifneq (,$(findstring musl-linux-,$(DEB_HOST_ARCH)))
  GENCTRL_OPTIONS = -Vlibc-dev:Provides=libc-dev -Vlinux-libc-dev:Depends=linux-libc-dev 
else
  GENCTRL_OPTIONS = -Vlinux-musl-dev:Recommends=linux-musl-dev
endif

%:
	dh $@ --parallel

debian/scripts/$(MUSL_TRIPLE).path: debian/scripts/config.path.in
	sed 's/@MUSL_TRIPLE@/$(MUSL_TRIPLE)/g' $< > $@
	cp debian/scripts/$(MUSL_TRIPLE).path debian/scripts/ld-musl-$(MUSL_ARCH).path

override_dh_auto_configure: debian/scripts/$(MUSL_TRIPLE).path
	dh_auto_configure -- --libdir=/usr/lib/$(MUSL_TRIPLE) --includedir=/usr/include/$(MUSL_TRIPLE) --host=$(DEB_HOST_GNU_TYPE)

override_dh_fixperms:
	dh_fixperms --exclude libc.so

override_dh_gencontrol:
	dh_gencontrol -- $(GENCTRL_OPTIONS)

override_dh_clean:
	rm -f debian/musl-dev.postinst debian/musl-dev.postrm
	dh_clean

override_dh_installdeb:
	sed 's/@MUSL_TRIPLE@/$(MUSL_TRIPLE)/g' \
		debian/musl-dev.postinst.in > debian/musl-dev.postinst
	sed 's/@MUSL_TRIPLE@/$(MUSL_TRIPLE)/g' \
		debian/musl-dev.postrm.in > debian/musl-dev.postrm
	dh_installdeb

