#! /usr/bin/make -f
# -*- makefile -*-
# Build rules for gcc (>= 3.4)
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

# This is the debhelper compatibility version to use.
export DH_COMPAT=4

build:
clean:
	dh_clean

install: 
	dh_testdir
	dh_testroot
	dh_clean -k
	dh_installdirs


USR_BIN_FILES?=catchsegv getconf getent ldd locale localedef rpcinfo tzselect zdump
USR_SBIN_FILES?=iconvconfig zic
USR_BIN_FILES_DEV?=rpcgen mtrace gencat
SBIN_FILES?=ldconfig
# Build architecture-dependent files here.
binary-arch: install
	dh_testdir
	dh_testroot

	# Install files to their package directories
	dh_installdocs
	dh_installchangelogs

	mkdir -p debian/libc6/{lib,sbin,usr/{lib,{,s}bin}}
	mkdir -p debian/libc6-dev/usr/{lib,bin}

	# Copy libraries (not c++)
	# The if picks all files of form libfoo.so libfoo.o or libfoo.a
	for f in `find $(LIBC_FILES_LIBS) -xtype f -maxdepth 1 | grep -v '++\.[^/]*$$' | grep -vE '.*/libgcc_s\.so\..*$$'`; do\
		if echo $$f | grep -qE '.*/[^.-]*\.(s?o|a)$$'; then \
			cp -d $$f debian/libc6-dev/usr/lib ;\
		else \
			cp -d $$f debian/libc6/lib ;\
		fi ;\
	done

	#Fix symlinks
	for f in `find debian/libc6-dev/usr/lib -type l`; do \
		if [ ! -f $$f ]; then \
			base=$$(basename `readlink $$f`); \
			if [ -a debian/libc6/lib/$$base ] || [ -a debian/libc6-dev/lib/$$base ]; then \
			ln -sf /lib/$$base $$f; \
			fi \
		fi \
	done

#	# Copy dirs to root
#	for dir in $(LIBC_FILES_ROOT); do \
#		cp -dR $$dir debian/libc6/
#	done
#	
	# Find gconv
	cp -Rd `find $(LIBC_FILES_LIBS) -type d -name gconv` debian/libc6/usr/lib/

	# Copy binaries
	for f in `find $(LIBC_FILES_BINS) | grep -E "/("$$(echo $(USR_BIN_FILES) | tr ' ' '|')")"$$`; do \
		cp -d $$f debian/libc6/usr/bin/ ;\
	done

	for f in `find $(LIBC_FILES_BINS) | grep -E "/("$$(echo $(USR_SBIN_FILES) | tr ' ' '|')")"$$`; do \
		cp -d $$f debian/libc6/usr/sbin/ ;\
	done
	
	for f in `find $(LIBC_FILES_BINS) | grep -E "/("$$(echo $(USR_BIN_FILES_DEV) | tr ' ' '|')")"$$`; do \
		cp -d $$f debian/libc6-dev/usr/bin/ ;\
	done
	
	for f in `find $(LIBC_FILES_BINS) | grep -E "/("$$(echo $(SBIN_FILES) | tr ' ' '|')")"$$`; do \
		cp -d $$f debian/libc6/sbin/ ;\
	done
	

	#Copy headers 
	mkdir -p debian/libc6-dev/usr/include
	cp -Rd $(HEADERS_DIR)/* debian/libc6-dev/usr/include
	rm -rf $(addprefix debian/libc6-dev/usr/include/,$(LINUX_HEADERS_SUBDIRS))

	dh_compress
	dh_fixperms

	chmod a+x debian/libc6/lib/ld[\.-]*so*

	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_link
	dh_makeshlibs -V

	# Build the packages
	dh_builddeb

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

