# Build template for 'busybox'.
pkgname=busybox
version=1.28.0
revision=1
hostmakedepends="perl"
checkdepends="zip"
short_desc="The Swiss Army Knife of Embedded Linux"
maintainer="Juan RP <xtraeme@voidlinux.eu>"
license="GPL-2"
homepage="http://www.busybox.net"
distfiles="${homepage}/downloads/busybox-$version.tar.bz2"
checksum=604553b7dbd59ded9e3ad7c6af49ed2cff599adf3e54d9463e5e0027b362019c

alternatives="
 awk:awk:/usr/bin/busybox
 hostname:hostname:/usr/bin/busybox
 sh:sh:/usr/bin/busybox
 ntpd:ntpd:/usr/bin/busybox
 ntpd:ntpd:/etc/sv/busybox-ntpd
 vi:vi:/usr/bin/busybox"

_cflags() {
	local t=$1
	local c="$CFLAGS"
	case $t in
		busybox-static) c="$c -static";;
	esac
	echo "$c"
}

do_configure() {
	mkdir -p src
	mv * src || true

	local t
	for t in busybox busybox-static; do
		mkdir -p $t
		make -C $t CFLAGS="$(_cflags $t)" KBUILD_SRC=${wrksrc}/src \
			-f ${wrksrc}/src/Makefile defconfig
		cp -f ${FILESDIR}/${t}.dotconfig ${t}/.config

		case "$XBPS_TARGET_MACHINE" in
		*-musl) sed -i -e /CONFIG_FEATURE_VI_REGEX_SEARCH/s/y/n/ \
				-e /CONFIG_FEATURE_MOUNT_NFS/s/y/n/ \
				${t}/.config;;
		esac

		if [ "$CROSS_BUILD" ]; then
			sed -e \
				"s,\(CONFIG_CROSS_COMPILER_PREFIX\).*,\1=\"${XBPS_CROSS_TRIPLET}-\",g" \
				-i ${t}/.config
		fi
		make -C $t prepare ${makejobs}
	done
	if [ "$SOURCE_DATE_EPOCH" ]; then
		# rewrite date with the one from the date wrapper.
		d=$(date +"%F %T %Z")
		sed -i "s/\(#define AUTOCONF_TIMESTAMP\).*/\1 \"$d\"/" */include/autoconf.h
	fi
}

do_build() {
	local t
	for t in busybox busybox-static; do
		make -C $t SKIP_STRIP=y CFLAGS="$(_cflags $t)" LFLAGS="$LDFLAGS" ${makejobs}
	done
}
do_check() {
	# Copy the testsuite into the busybox and it's static counterpart
	# directory
	cp -r src/testsuite busybox
	cp -r src/testsuite busybox-static

	# This is required by the testsuite
	cp src/scripts/echo.c busybox/scripts
	cp src/scripts/echo.c busybox-static/scripts

	# Run testsuite for busybox
	cd busybox/testsuite
	SKIP_KNOWN_BUGS=yes ./runtest -v

	cd ../../

	# run testsuite for busybox-static
	cd busybox-static/testsuite
	SKIP_KNOWN_BUGS=yes ./runtest -v
}
do_install() {
	vbin busybox/busybox_unstripped busybox
	vman busybox/docs/busybox.1
	vsv busybox-ntpd
}

busybox-static_package() {
	short_desc+=" (statically linked)"
	pkg_install() {
		vbin busybox-static/busybox busybox.static
	}
}
